控制ggplot中的图例

时间:2017-06-03 19:46:20

标签: r ggplot2 legend

我编写的代码使用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")

情节如下。我已经注释了我的目标: enter image description here

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

您的建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

有人向你投票可能是因为没有数据集&#34; german&#34;就无法重现你所做的事情。您应该尝试翻译您的问题以使用每个人都有权访问的数据集。

除了使用数据集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")

enter image description here

要更改图例中类别的顺序,请包含一行代码,这样可以将因子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已经是一个因素。另外,在末尾添加行+指南(颜色= 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)

enter image description here