ggplot2:无法使用guide_legend在多行中显示图例文本

时间:2015-03-27 14:46:17

标签: r ggplot2 legend geom-bar

我正在尝试为下面的代码( yrly_data 变量)中的数据创建直方图。

> yrly_data
   Series Dates         YTD
1    Fund  2013  0.08434377
2    Fund  2014  0.07869951
3  Index1  2013  0.32361649
4  Index1  2014  0.13653722
5  Index2  2013 -0.02017807
6  Index2  2014  0.05941566
7  Index3  2013 -0.02011621
8  Index3  2014  0.07471164
9  Index4  2013  0.11662013
10 Index4  2014 -0.20183881
> dput(yrly_data)
structure(list(Series = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 
4L, 5L, 5L), .Label = c("Fund", "Index1", "Index2", "Index3", 
"Index4"), class = "factor"), Dates = c(2013L, 2014L, 2013L, 
2014L, 2013L, 2014L, 2013L, 2014L, 2013L, 2014L), YTD = c(0.084343775, 
0.078699508, 0.323616491, 0.136537222, -0.020178073, 0.059415661, 
-0.020116206, 0.074711644, 0.116620129, -0.20183881)), .Names = c("Series", 
"Dates", "YTD"), class = "data.frame", row.names = c(NA, -10L
))

我的代码如下:

library(ggplot2)
rcnt = 3 # number of legend rows
yrly_data$YTD = as.numeric (yrly_data$YTD)
hgrm = ggplot(data = yrly_data, aes(x = Dates, fill = Series, weight = YTD))
hgrm = hgrm + geom_bar(position = 'dodge', colour="black") # create clustered bar chart
hgrm = hgrm + theme(legend.position = 'top') + guides(colour = guide_legend(nrow = rcnt))
plot(hgrm)

我收到此错误:

stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
Warning message:
In loop_apply(n, do.ply) :
  position_dodge requires constant width: output may be incorrect

除了我将传奇文本放在一行之外,一切都有效。任何想法为什么以及如何解决这个问题?

enter image description here

1 个答案:

答案 0 :(得分:0)

您的指南指的是不是fill的颜色,这是图例所代表的美学,将您的最后一行更改为:

hgrm = hgrm + theme(legend.position = 'top') + guides(fill = guide_legend(nrow = rcnt))

应该为你效劳。