【问题标题】:geom_point and geom_col fill color change and legend label changegeom_point 和 geom_col 填充颜色变化和图例标签变化
【发布时间】:2018-02-15 08:21:23
【问题描述】:

我的数据框看起来像这样:

df = data.frame(
  measure = c("Measure A","Measure B","Measure C"),
  overall = c(9, 5, 11),
  company = c(4,6,3)
)

我正在尝试为公司绘制条形图,并使用 geom_point, "lines" 作为整体。出于某种原因,即使我的代码指定了图例的公司颜色填充和标签,它也不会改变:

ggplot(df, aes(measure)) + geom_col(aes(y=company, fill="company")) + geom_point(aes(y=overall, color="overall"), size=8, shape=124) +
  scale_color_manual(values=c("company" = "yellow", "overall"="blue"),labels=c("company" = "Your Company", "overall"= "Overall Benchmark")) +
  coord_flip()+ guides(size=FALSE) + theme(legend.box="horizontal",legend.key=element_blank(), legend.title=element_blank(),legend.position="top")

条形图保持红色,图例显示公司无论如何。有没有办法解决这个问题?

【问题讨论】:

  • 您使用了fill 作为条形图。 scale_color_manual 用于color,而不是fill。使用scale_fill_manual 更改fill 颜色和标签。
  • 这完全有道理。

标签: r ggplot2


【解决方案1】:

只需删除 fill = "company" 中的引号即可。它应该可以按您的预期工作。

这里又是完整的源代码,但有了上面提到的修复,并且还尊重Google's R Style Guide 的缩进,它确实有助于提高可读性并找到这样的遗漏部分:)。

df = data.frame(
measure = c("Measure A", "Measure B", "Measure C"),
overall = c(9, 5, 11),
company = c(4, 6, 3)
)

ggplot(df, aes(measure)) +
geom_col(aes(y    = company,
            fill  = company)) +
geom_point(aes(y      = overall,
                color = "overall"),
            size = 8,
            shape = 124) +
scale_color_manual(
    values = c("company" = "yellow",
            "overall"    = "blue"),
    labels = c("company" = "Your Company",
            "overall"    = "Overall Benchmark")
) +
coord_flip() +
guides(size = FALSE) +
theme(
    legend.box      = "horizontal",
    legend.key      = element_blank(),
    legend.title    = element_blank(),
    legend.position = "top"
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2022-01-02
    • 2022-07-07
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多