ggplot图例关键颜色和项目 [英] ggplot legend key color and items
问题描述
使用以下数据框:
sdf <-data.frame(小时= gl(n = 3,k = 1,length = 9,labels = c(0,2,4)),
count = c(4500,1500,2600,4000,800,200,1500,50,20),
machine = gl (n = 3,k = 3,长度= 9,标签= c(A,B,C)))
使用以下任一脚本可以生成以下图表:
ggplot(data = sdf,aes(x = hours,y = count,group = machine,fill = machine))+
geom_area(data = sdf [sdf $ machine ==A,])+
geom_area data = sdf [sdf $ machine ==B,])+
geom_area(data = sdf [sdf $ machine ==C,])
ggplot(data = sdf ,aes(x = hours,y = count,group = machine,fill = machine))+
geom_area(position =dodge)
然而,当填充颜色改变时,图例中的项目消失。
ggplot(data = sdf,aes(x =小时,y = count,group = machine,fill = machine))+
geom_area(data = sdf [sdf $ machine ==A,])+
geom_area(data = sdf [sdf $ machine ==B,],fill =darkorchid)+
geom_area(data = sdf [sdf $ machine ==C,])
理想情况下,传说应该显示颜色变化。
问题:哪个脚本可以在图例中创建项目以及为这些项目提供颜色控制?
您可以使用 scale _
X _manual(values =
(无论))
。在这里你想 scale_fill_manual
。
ggplot(data = sdf,aes( x =小时,y = count,group = machine,fill = machine))+
geom_area(position =dodge)+
scale_fill_manual(values = c(red,darkorchid绿色))
请注意,通常要让 ggplot
为你分组数据,就像你在第二次调用 ggplot
时所做的那样(这就是 group
参数确实)。正如你在第一个例子中所做的那样,分别提供每个'切片'数据,几乎违背了 ggplot2
的目的,应该避免。
Using the following data frame:
sdf<-data.frame(hours=gl(n=3,k=1,length=9,labels=c(0,2,4)),
count=c(4500,1500,2600,4000,800,200,1500,50,20),
machine=gl(n=3,k=3,length=9,labels=c("A","B","C")))
The following graph can be produced using either of these scripts:
ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
geom_area(data=sdf[sdf$machine=="A",])+
geom_area(data=sdf[sdf$machine=="B",])+
geom_area(data=sdf[sdf$machine=="C",])
ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
geom_area(position="dodge")
However, when the fill color is changed, the item in the legend disappears.
ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
geom_area(data=sdf[sdf$machine=="A",])+
geom_area(data=sdf[sdf$machine=="B",],fill="darkorchid")+
geom_area(data=sdf[sdf$machine=="C",])
Ideally, the legend should show the color change.
Question: What script can create items in a legend as well as offer color controls for those items?
You can adjust the values assigned to any aesthetic using scale_
X_manual(values=
(whatever))
. Here you want scale_fill_manual
.
ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+
geom_area(position="dodge") +
scale_fill_manual(values=c("red", "darkorchid", "green"))
Note that, as a rule, you want to let ggplot
group the data for you, as you have done in your second ggplot
call (This is what the group
argument does). Supplying each 'slice' of data separately, as you have done in your first example, pretty much defeats the purpose of ggplot2
, and should be avoided.
这篇关于ggplot图例关键颜色和项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!