【问题标题】:Controlling the legend in ggplot控制ggplot中的图例
【发布时间】:2017-06-03 19:46:20
【问题描述】:

我编写了代码,使用 ggplot 为两个类绘制某个数值变量的密度图。但我无法处理传奇的外观。我的代码如下:

mu <- ddply(german, "Class", summarise, grp.mean=mean(Credit_amount))


ggplot(german, aes(x=Credit_amount, fill=as.factor(Class))) +
  geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
  geom_density(alpha=0.6)+
  geom_vline(data=mu, aes(xintercept=grp.mean, color= as.factor(Class)),
             size = 2, alpha = 0.6)+
  labs(title="Credit_amount for the Two Classes (Good and Bad Creditors",x="Credit_amount", y = "Density") +
scale_fill_manual(limits=c("1", "0"), labels = c("Bad Creditors", "Good Creditors"), values = c("blue", "red"))
+ labs(fill="Class of Customers")

剧情如下。我已经注释了我要进行的更改:

我做错了什么?我应该怎么做?

您的建议将不胜感激。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    可能有人对您投了反对票,因为如果没有“德语”数据集,就无法重现您所做的事情。您应该尝试翻译您的问题以使用每个人都可以访问的数据集。

    这大致就是你所拥有的,除了使用数据集 mtcars:

    library(plyr)
    library(ggplot2)
    data(mtcars)
    mtcars$cyl = paste0(mtcars$cyl, ' cyl')
    mu <- ddply(mtcars, "cyl", summarise, grp.mean=mean(mpg))
    ggplot(mtcars, aes(x=mpg, fill=as.factor(cyl))) +
      geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
      geom_density(alpha=0.6)+
      geom_vline(data=mu, aes(xintercept=grp.mean, color= as.factor(cyl)),
                 size = 2, alpha = 0.6)+
      labs(title="Title",x="mpg", y = "Density") +
      scale_fill_manual(limits=c('4 cyl', '6 cyl', '8 cyl'), 
                        labels = c("4 cyl", "6 cyl", '8 cyl'), 
                        values = c("red", "green", 'blue')) + 
      labs(fill="Class of Customers")
    

    要更改图例中类别的顺序,请包含这样一行代码,它将因子 cyl 的级别设置为所需的顺序:

    mtcars$cyl = factor(mtcars$cyl, levels = c('8 cyl', '6 cyl', '4 cyl'))
    mu <- ddply(mtcars, "cyl", summarise, grp.mean=mean(mpg))
    

    然后在 ggplot 代码中,删除对 as.factor(cyl) 的引用,并简单地放入 cyl,因为 cyl 已经是一个因子。此外,在末尾添加行 +guides(color=FALSE) 以删除不需要的图例:

    ggplot(mtcars, aes(x=mpg, fill=cyl)) +
      geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
      geom_density(alpha=0.6)+
      geom_vline(data=mu, aes(xintercept=grp.mean, color= cyl),
                 size = 2, alpha = 0.6 )+
      labs(title="mtcars example",x="mpg", y = "Density") +
      scale_fill_manual(limits=c('8 cyl', '6 cyl', '4 cyl'), 
                        labels = c("8 cyl", "6 cyl", '4 cyl'), 
                        values = c("red", "green", 'blue')) + 
      labs(fill="Class of Customers")+
      guides(color=FALSE)
    

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2015-07-04
      • 2012-07-05
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多