GGplot scale_fill_discrete不创建图例

时间:2017-10-31 08:01:38

标签: r ggplot2

我在先前的stackoverflow帖子中使用了这个代码,之前使用了一个图例,我之前使用了我想要的图形,但是现在我使用完全相同的代码但是我没有在我的条形图上得到一个图例。

dput(year.dat2)
structure(list(year = structure(c(1136044800, 1167577200, 1199113200, 
1230735600, 1262275200, 1136044800, 1167577200, 1199113200, 1230735600, 
1262275200, 1136044800, 1167577200, 1199113200, 1230735600, 1262275200
), class = c("POSIXct", "POSIXt"), tzone = ""), variable = structure(c(1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("SM1", 
"SM2", "SM3"), class = "factor"), value = c(1.24863586758821, 
1.23185757914453, 1.10997352162401, 1.13683917747257, 0.987520605867152, 
2.21498726809749, 1.6378992693761, 1.25635623380691, 1.13585705516765, 
1.10169569342842, 7.40955802109858, 5.7940698875978, 6.03438772314438, 
6.82271157830123, 7.24402375195127)), row.names = c(NA, -15L), .Names = 
c("year", 
"variable", "value"), class = "data.frame")

ggplot(year.dat2, aes(x = year, y = value, fill = factor(variable))) +
  geom_bar(stat = "identity", position = "dodge")+
  scale_fill_discrete(name = "variable",
                      breaks = c(1, 2, 3),
                      labels = c("SM1", "SM2", "SM3")) +
  xlab("year") + 
  ylab("yearly Sub Mean")

结果情节:

plot

1 个答案:

答案 0 :(得分:1)

移除breaks中的scale_fill_discrete,它们与用作填充variable的因子aes数据的值不对应。

这是您想要的代码:

ggplot(year.dat2, aes(x = year, y = value, fill = factor(variable))) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_discrete(name = "variable",
                  labels = c("SM1", "SM2", "SM3")) +
  xlab("year") + 
  ylab("yearly Sub Mean")

注1:您甚至不需要labels参数,因为您没有重命名variable类别。 scale_fill_discrete(name = "variable")就足够了,或者只需labs(fill="variable")即可更改图例标题。

注意2:在原始帖子中,您链接到此SO问题:How to get a barplot with several variables side by side grouped by a factor

此处,示例代码breaks中的scale_fill_discrete(name="Gender", breaks=c(1, 2), labels=c("Male", "Female"))实际上引用了原始df中gender的值。同时,labels用于在图例中将1重命名为Male,将2重命名为Female

  Group.1      tea     coke     beer    water gender
1       1 87.70171 27.24834 24.27099 37.24007      1
2       2 24.73330 25.27344 25.64657 24.34669      2

另一方面,1,2,3数据中没有variable值与您在原始代码中设置的breaks相匹配,这就是为什么您的图例不是作图。

为了好玩,以下是您可以在数据集中使用breakslabels的示例:

ggplot(year.dat2, aes(x = year, y = value, fill = factor(variable))) +
  geom_bar(stat = "identity", position = "dodge")+
  scale_fill_discrete(name = "variable",
                  breaks = c("SM2", "SM3", "SM1"),
                  labels = c("SM2 new label", "SM3 new label", "SM1 new label")) +
  xlab("year") + 
  ylab("yearly Sub Mean")