我尝试用ggplot2在barplot中可视化两个离散变量,分别使用fill
和alpha
。这样做的标准方法如下:
#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")
默认图例根据两种不同的呈现方式进行分组(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"))
所以现在我只能将三个图例条剪切并粘贴到主图上,例如在inkscape中,以产生所需的结果:
如何以合适的方式对此进行编程?
答案 0 :(得分:4)
您可以使用channelRead
绘制自定义图例:
scale_fill_manual
编辑以下是@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)