我想绘制一个堆叠的条形图,如附图,但我希望颜色在类别aa,bb和cc之间变化.具体来说,我希望bb中的灰色块为红色,cc中的灰色块为绿色.以下代码作为一个简单示例,说明了我已经尝试过的内容:
aa=c(0.2,0.6,0.1,0.1)
bb=c(0.4,0.5,0.05,0.05)
cc=c(0.5,0.25,0.1,0.15)
x=cbind(aa,bb,cc)
x #the data
aa bb cc
[1,] 0.2 0.40 0.50
[2,] 0.6 0.50 0.25
[3,] 0.1 0.05 0.10
[4,] 0.1 0.05 0.15
Run Code Online (Sandbox Code Playgroud)
默认行为,所有块在每个类别中具有相同的颜色
col=rep(c("white","grey"),2)
col
# [1] "white" "grey" "white" "grey"
barplot(x,col=col)
Run Code Online (Sandbox Code Playgroud)
但我希望灰色块bb是红色,灰色块cc是绿色
col=cbind(rep(c("white","grey"),2),rep(c("white","red"),2),rep(c("white","green"),2))
col
[,1] [,2] [,3]
[1,] "white" "white" "white"
[2,] "grey" "red" "green"
[3,] "white" "white" "white"
[4,] "grey" "red" "green"
barplot(x,col=col) #not working
col=c(rep(c("white","grey"),2),rep(c("white","red"),2),rep(c("white","green"),2))
col
[1] "white" "grey" "white" "grey" "white" "red" "white" "red" "white" "green" "white" …Run Code Online (Sandbox Code Playgroud) 我创建了一个堆积条形图,描绘了市政当局在几年内(= x轴)的议会席位(= y轴)的分布.使用的代码和一些数据如下.不幸的是,我没有足够的积分来发布图表.
不同的政党也与称为"意识形态"的变量相关联,作为不同政治取向的类别("进步","中等","保守").
我希望以这样的方式修改颜色,例如所有保守派派对都有不同的蓝调; 所有进步党派各种绿色; 和所有温和派对,例如不同种类的红色;
意识形态的变量在同一个数据帧(y)中.
任何提示如何进行此修改?我已经尝试过color = factor(意识形态)和group =意识形态,但无济于事.我也知道这个相关的条目在ggplot中使用预定义的调色板,但它并不特别与我的问题有关.
非常感谢.
使用命令:
municipality.plot <- ggplot(y, aes(x=as.factor(year), y=seats, fill=party, color=party)) +
geom_bar(bandwidth=1, stat="identity", group="party", position="fill") +
labs(x="year", y="% of seats for municipality")
Run Code Online (Sandbox Code Playgroud)
样本数据:
year district.id party seats ideology
1 2012 127 Stranka Pravde I Razvoja Bosne I Hercegovine 1 p
2 2012 127 Savez Za Bolju Buducnost (SBB) 3 p
3 2008 127 Stranka Demokratske Akcije (SDA) 13 p
4 2004 127 Stranka Demokratske Akcije (SDA) 14 …Run Code Online (Sandbox Code Playgroud)