r ggplot2:在条形图中对图例进行分组

时间:2017-08-15 20:47:01

标签: r ggplot2 bar-chart legend

我尝试用ggplot2在barplot中可视化两个离散变量,分别使用fillalpha。这样做的标准方法如下:

#creating data and building the basic bar plot
library(ggplot2)
myleg<-read.csv(text="lett,num
a,1
a,2
b,1
b,2
h,1
h,2
h,3
h,4")
ggplot(myleg,aes(lett,alpha=factor(num),fill=lett)) +geom_bar(position=position_stack(reverse=T)) +scale_alpha_discrete(range=c(1,.1), name="alpha legend",labels=c("alpha lab 4","alpha lab 3","alpha lab 2", "alpha lab 1")) +labs(title="initial bar plot for data")

initial bar plot of data

默认图例根据两种不同的呈现方式进行分组(lett和灰度的着色,或num的不透明度)。

我需要将图例分组为图表上的数据条。即三个颜色条,每个颜色条具有改变的α水平。部分解决方案是分别生成具有所需三个图例条的图,如下所示:

ggplot(myleg,aes(lett,alpha=factor(num),fill=lett)) +geom_bar(position="stack",fill="#f8766d") +scale_alpha_discrete(name="red legend",labels=c("red lab 2","red lab 1"),breaks=c("3","4"))
ggplot(myleg,aes(lett,alpha=factor(num),fill=lett)) +geom_bar(position="stack",fill="#00ba38") +scale_alpha_discrete(name="green legend",labels=c("green lab 2","green lab 1"),breaks=c("3","4"))
ggplot(myleg,aes(lett,alpha=factor(num),fill=lett)) +geom_bar(position="stack",fill="#619cff") +scale_alpha_discrete(name="blue legend",labels=c("blue lab 4","blue lab 3","blue lab 2", "blue lab 1"))

输出是: artificially created plots with needed legend strips

所以现在我只能将三个图例条剪切并粘贴到主图上,例如在inkscape中,以产生所需的结果:

final plot with desired legend

如何以合适的方式对此进行编程?

1 个答案:

答案 0 :(得分:4)

您可以使用channelRead绘制自定义图例:

scale_fill_manual

enter image description here

编辑以下是@astrsk发布的(新)问题的解决方案(在他/她更改初始问题之后)。

df <- mtcars
df$cyl <- factor(df$cyl)
df$vs <- factor(df$vs)

library(ggplot2)    
p <- ggplot(df,aes(x=cyl, fill=interaction(cyl,vs))) + geom_bar(position="stack") 

# Breaks
brks <- levels(interaction(df$cyl,df$vs))

# Values - Colors
library(scales)
pal <- hue_pal()(3)
cls <- as.character(c(sapply(pal,alpha,0.3),sapply(pal,alpha,1)))

# Labels
lbls <- paste(levels(df$cyl), "-", rep(levels(df$vs),each=3))

p  + scale_fill_manual(name ='Cyl - Vs', breaks=brks, values=cls, labels=lbls)

enter image description here