geom_point和geom_col填充颜色更改和图例标签更改

时间:2017-09-06 18:28:48

标签: r ggplot2

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

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

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

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")

这些酒吧保持红色,而传说中的公司无论如何。有办法解决这个问题吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

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

这又是完整的源代码,但是有了提到的修复,并且尊重Argument unpacking的缩进,它确实有助于提高可读性并找到像这样的遗漏片段:)。

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"
)

Google's R Style Guide