【问题标题】:Unable to customize legend in ggplot无法在 ggplot 中自定义图例
【发布时间】:2015-04-28 03:07:15
【问题描述】:

我正在使用ggplot(我的代码如下)绘制年度需求,但我无法为该图添加颜色图例。我的 data.frame 有“Zone”和“TotalDemand”(只有 2 列),我有三个 data.frames 三年(“sales12”、“sales13”和“sales14”)。

ggplot() + 
geom_point(data=sales12, aes(x=factor(Zone), y=TotalDemand/1000), 
           color='green',size=6, shape=17) +
geom_point(data=sales13, aes(x=factor(Zone), y=TotalDemand/1000), 
           color='red',size=6, shape=18)+
geom_point(data=sales14, aes(x=factor(Zone), y=TotalDemand/1000), 
           color='black',size=4, shape=19) + 
labs(y='Demand (in 1000s)',x='Zones') +
scale_colour_manual(name = 'the colour', 
                    values = c('green'='green', 'black'='black', 'red'='red'), 
                    labels = c('12','13','14'))

请帮我找出我的错误。

【问题讨论】:

  • 可能是我的问题不清楚,所以它被否决了。我已经用了三种颜色 3 年了,我不能把它们当作传说。在在这里发布我的问题之前,我尝试查看相关帖子上提供的帮助。 :)
  • 你不需要像这样geom_point 上锅三遍。为年份创建一个变量,在 aes 中,您可以使用它来为点着色。它非常基本的ggplot。这表明您在发布此问题之前尚未阅读任何内容。尽管如此,如果你能提供一个可重现的例子,你就会得到答案。
  • 如果你想要一个图例,你必须在aes中映射一些东西来着色。

标签: r ggplot2 legend


【解决方案1】:

使用一个非常小的示例数据框 df,我将其融合为ggplot

dput(df)
structure(list(Zone = structure(1:4, .Label = c("Alpha", "Baker", 
"Charlie", "Delta"), class = "factor"), TotalDemand = c(90L, 
180L, 57L, 159L), sales12 = c(25L, 40L, 13L, 50L), sales13 = c(30L, 
60L, 16L, 55L), sales14 = c(35L, 80L, 28L, 54L)), .Names = c("Zone", 
"TotalDemand", "sales12", "sales13", "sales14"), class = "data.frame", row.names = c(NA, 
-4L))

df.m <- melt(df, id.vars = "Zone", measure.vars = c("sales12", "sales13", "sales14"))

ggplot(df.m, aes(x=factor(Zone), y=value, color = variable )) + 
  geom_point(size=6, shape=17) +
  labs(y='Demand (in 1000s)',x='Zones') +
  scale_colour_manual(values = c('green', 'black', 'red'))

您可以调整点的大小、形状和颜色,添加标题等。例如,您的图例也可以位于底部。

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2022-06-16
    • 2021-08-14
    • 1970-01-01
    • 2020-07-28
    • 2018-09-15
    相关资源
    最近更新 更多