首页 > 解决方案 > ggplot2图例标签没有改变

问题描述

我一直在寻找为什么我的图例标签没有改变的答案。到目前为止,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")

机器兴趣图

标签: rggplot2graph

解决方案


正如@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")

你得到: 在此处输入图像描述

因此,根据您的代码,您应该通过以下方式获得正确的绘图:

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"))

如果这对您不起作用,请考虑提供您的数据集的可重现示例(请参阅此处:如何制作出色的 R 可重现示例


推荐阅读