【问题标题】:Coloring the vertical lines by Class in ggplot在ggplot中按类为垂直线着色
【发布时间】:2017-12-15 00:09:04
【问题描述】:

我想按类绘制变量的分布,并添加垂直线来表示每个类定义的子集的均值,并让它们按类着色。虽然我成功按类为分布着色,但垂直线显示为灰色。有关可重现的示例,请参见下文:

library(data.table)
library(ggplot2)
library(ggthemes)

data(mtcars)
setDT(mtcars)
mtcars[, am := factor(am, levels = c(1, 0))]
mean_data <- mtcars[, .(mu = mean(hp)), by = am]

ggplot(mtcars, aes(x = hp, fill = am , color = am)) +
  geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) + guides(color = FALSE) +
  geom_density (alpha = 0.5)+ 
  geom_vline(data = mean_data, xintercept = mean_data$mu, aes(color = as.factor(mean_data$am)), size = 2, alpha = 0.5) +
  ggtitle("Hp by am") + scale_fill_discrete(labels=c("am" , "no am")) +
  labs(fill = "Transmission") + theme_economist()

此代码呈现以下图:

您的建议将不胜感激。

【问题讨论】:

    标签: r ggplot2 colors line


    【解决方案1】:

    您需要在您的aes 调用中包含xintercept 映射,以便ggplot 正确映射所有美学:

    ggplot(mtcars, aes(x = hp, fill = am , color = am)) +
        geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) + guides(color = FALSE) +
        geom_density (alpha = 0.5)+ 
        geom_vline(data = mean_data, aes(xintercept = mu, color = as.factor(am)), size = 2, alpha = 0.5) +
        ggtitle("Hp by am") + scale_fill_discrete(labels=c("am" , "no am")) +
        labs(fill = "Transmission") + theme_economist()
    

    您在geom 调用中放入的任何不在aes 中的内容都将被视为一次性值,并且不会将所有映射美学应用到它。

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多