ggplot中的两个填充变量
Two fill variable in ggplot
我想创建一个 ggplot
,它使用两个变量以不同的方式填充。基于这个solution我做了
x = c("Band 1", "Band 2", "Band 3")
y1 = c("1","2","3")
y2 = c("2","3","4")
to_plot <- data.frame(x=x,y1=y1,y2=y2)
melted<-melt(to_plot, id="x")
ggplot(melted,aes(x=x,y=value,fill=variable)) +
geom_bar(stat="identity",position = "identity", alpha=.3)
但我想用不同的方式为每个 Band
值着色,并将 y1
实现为带有给定 [= 颜色边框的白色条,而不是 alpha
参数13=] 和 y2
作为颜色为给定 Band
的条形图。怎么做?
这是我的最佳尝试。由于您的情节不是 "ggplot-canonical" w.r.t,因此您需要在这里和那里进行多次覆盖。到 aes
映射。
# extra variable to map to fill
melted$col <- ifelse(melted$variable == "y1", "white", melted$x)
# reorder appearance, so that y1 is plotted after y2
melted <- with(melted, melted[order(-as.numeric(variable)), ])
ggplot(melted, aes(x=x, y=value, fill=col, color=x, alpha=variable)) +
geom_bar(stat="identity", position="identity", size=2) +
scale_fill_manual(values = c("red", "green", "blue", "white"), guide=FALSE) +
scale_color_manual(values = c("red", "green", "blue")) +
scale_alpha_manual(values = c(1, 0.5), guide=FALSE)
我想创建一个 ggplot
,它使用两个变量以不同的方式填充。基于这个solution我做了
x = c("Band 1", "Band 2", "Band 3")
y1 = c("1","2","3")
y2 = c("2","3","4")
to_plot <- data.frame(x=x,y1=y1,y2=y2)
melted<-melt(to_plot, id="x")
ggplot(melted,aes(x=x,y=value,fill=variable)) +
geom_bar(stat="identity",position = "identity", alpha=.3)
但我想用不同的方式为每个 Band
值着色,并将 y1
实现为带有给定 [= 颜色边框的白色条,而不是 alpha
参数13=] 和 y2
作为颜色为给定 Band
的条形图。怎么做?
这是我的最佳尝试。由于您的情节不是 "ggplot-canonical" w.r.t,因此您需要在这里和那里进行多次覆盖。到 aes
映射。
# extra variable to map to fill
melted$col <- ifelse(melted$variable == "y1", "white", melted$x)
# reorder appearance, so that y1 is plotted after y2
melted <- with(melted, melted[order(-as.numeric(variable)), ])
ggplot(melted, aes(x=x, y=value, fill=col, color=x, alpha=variable)) +
geom_bar(stat="identity", position="identity", size=2) +
scale_fill_manual(values = c("red", "green", "blue", "white"), guide=FALSE) +
scale_color_manual(values = c("red", "green", "blue")) +
scale_alpha_manual(values = c(1, 0.5), guide=FALSE)