ggplot2图例标签未更改

时间:2020-02-08 14:33:26

标签: r ggplot2 graph

我一直在寻找答案,为什么我的图例标签没有更改。到目前为止,labs()是我设法更改标题的唯一方法。 scale_fill_discreate / manual()似乎不起作用。

有什么想法吗?

ggplot(na.omit(VMSdat), aes(x = mach_type, fill=mach_type, y= interest_lvl)) +
  labs(title = "Average Level of Interest in Studio machines by  Medical\nand Vetrinarian School students", x = "Machine Type", y = "Level of Interest")+
  labs(fill="Machine Type")+
  scale_fill_manual(name = "Machine type", labels=c("CNC milling", "Die Cutter", "Electronics", "3D Printing","3D Scanning", "Vacuum Former", "Virtual Reality"))+
  facet_wrap(~schoolName)+
  geom_bar(position=position_dodge(), stat="summary", fun.y="mean")+
  coord_cartesian(ylim = c(.2,5)) +
  theme(axis.title=element_text(size=12))+ 
  theme(legend.title = element_text(size=12), legend.text=element_text(size=11))+
  scale_fill_brewer(palette="Set1")

Machine interest graph

1 个答案:

答案 0 :(得分:0)

@Ben指出,您的代码中有两个scale_fill...函数。因此,似乎正在取代第一个正在做的事情。 因此,一种可行的解决方案是合并它们并在scale_fill_brewer中传递所有参数。

没有可重复的数据集示例,很难确定该解决方案将完全适合您的数据。在这里,我使用内部数据集iris来说明如何在使用scale_fill_brewer时更改标签和名称:

library(ggplot2)
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species))+
  geom_bar(stat = "identity")+
  scale_fill_brewer(palette = "Set1",
                    labels = c("A","B","C"),
                    name = "New Title")

您将获得: enter image description here

因此,根据您的代码,您应该这样做:

ggplot(na.omit(VMSdat), aes(x = mach_type, fill=mach_type, y= interest_lvl)) +
  labs(title = "Average Level of Interest in Studio machines by  Medical\nand Vetrinarian School students", x = "Machine Type", y = "Level of Interest")+
  labs(fill="Machine Type")+
  facet_wrap(~schoolName)+
  geom_bar(position=position_dodge(), stat="summary", fun.y="mean")+
  coord_cartesian(ylim = c(.2,5)) +
  theme(axis.title=element_text(size=12))+ 
  theme(legend.title = element_text(size=12), legend.text=element_text(size=11))+
  scale_fill_brewer(palette="Set1",
                    name = "Machine type", 
                    labels=c("CNC milling", "Die Cutter", "Electronics", "3D Printing","3D Scanning", "Vacuum Former", "Virtual Reality"))

如果这对您不起作用,请考虑提供可复制的数据集示例(请参见此处:How to make a great R reproducible example