【问题标题】:ggplot2: cannot display the legend text in multiple rows using guide_legendggplot2:无法使用 guide_legend 在多行中显示图例文本
【发布时间】:2015-03-27 14:46:16
【问题描述】:

我正在尝试为如下所示的数据创建一个直方图(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

除了我在一行中获得图例文本外,一切正常。任何想法为什么以及如何解决这个问题?

【问题讨论】:

    标签: r ggplot2 legend geom-bar


    【解决方案1】:

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

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

    应该适合你。

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-17
      • 2020-01-20
      • 2018-04-14
      • 2023-02-22
      • 2020-10-13
      • 1970-01-01
      相关资源
      最近更新 更多