R ggplot在堆积条形图中更改一个变量的颜色 [英] R ggplot Changing color of one variable in stacked bar graph
问题描述
我有一个数据框 D
,如下所示:
I have a data frame D
that look like this:
Track <- c(0,0,0,-1,1,1)
Length <- c(1,1,2,1,3,1)
Legend <- c("A","B","A","C","B","C")
D <- data.frame(Track,Length,Legend)
D
# Track Length Legend
# 0 1 A
# 0 1 B
# 0 2 A
# -1 1 C
# 1 3 B
# 1 1 C
我目前使用此代码来绘制它:
I am currently using this code to plot it:
ggplot(Z, aes(x=Track, y=Length, fill=Legend)) +
geom_bar(stat='identity') + geom_point() + expand_limits(x=0,y=0) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))
图表看起来像这样:
And the graph looks like this:
然而,我想将白色分配给变量B.这种操作是否可行?此外,为了简单起见,我在本文中使用了虚拟数据。我将要使用的实际数据可能在Legend下有10个或更多不同的变量,因此写出每个十六进制颜色看起来不是一个干净的选项。
However I want to assign the color white to variable B. Is this manipulation possible? Additionally I am using dummy data for simplicity's sake in this post. The actual data that I will be using may have 10 or more different variables under Legend, so writing out each hex color doesn't look like a clean option.
谢谢寻求帮助
Thank you for the help
推荐答案
这是否会产生您所追求的内容?
$ b
Does this produce what you're after?
x <- length(levels(factor(Legend)))
x.colors <- hcl(h=seq(15,375,length=(x+1)),l=65,c=100)[1:x]
x.colors[x] <- "white"
ggplot(D, aes(x=Track, y=Length, fill=Legend)) +
geom_bar(stat='identity',colour="black") + geom_point() + expand_limits(x=0,y=0) +
scale_fill_manual(values=x.colors) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour ="black"))
I添加 scale_fill_manual()
给A,B和C分配颜色。我还添加了 color =black
code> geom_bar()。你可以在第二部分和没有第二部分的情况下尝试,看看你的想法。
I added scale_fill_manual()
assigning colors to A, B, and C. I also added colour="black"
to geom_bar()
. You could try it with and without the second part and see what you think.
这篇关于R ggplot在堆积条形图中更改一个变量的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!