ggplot中的数据顺序和颜色

2024-04-13

我在数据框中有经理的资产

Date        C       B       A       E       D
2011-06-30 20449251 2011906       0       0       0
2011-09-30 20766092 1754940       0       0       0
2011-12-31 15242138 1921684       0       0       0
2012-03-31 15811841 2186571       0       0       0
2012-06-30 16221813 2026042 2423039 2419517       0
2012-09-30 16155686 2261729 2563734 1160693       0
2012-12-31 16297839 2231341 2592015 1151989       0
2013-03-31 14627046 2441132 2769681 1249464       0
2013-06-30 14186185 2763985 2615053 1260893       0
2013-09-30 14039954 2780167 2698988 1264244       0
2013-12-31 13832117 3081687 2962113 1318903       0
2014-03-31 14177177 3133202 3077684 1353243       0
2014-06-30 14503900 3235089 3196623 1415319       0
2014-09-30 12561057 3227862 3048216 1413446 2073068

然后我融化并绘制以获得堆积面积图

library('ggplot2')
library('reshape2')
colorscheme = scale_fill_brewer(type="qual",palette = 2)

df = melt(data,id.var="Date",variable.name="Manager")
df[,3] = as.numeric(df[,3])

#Stacked Area
layout(c(1,1))
p = ggplot(df,aes(x=Date,y=value,group=Manager,fill=Manager))+
  geom_area(position="fill") + colorscheme 
print(p)

这很有效:

现在我想要最后一行的饼图(即当前日期)

df1 = data[nrow(data),-1]
df1 = as.data.frame(t(df1))
colnames(df1) = "AUM"

p = ggplot(df1,aes(x=1,y=df1$AUM,fill=rownames(df1))) + 
  geom_bar(stat="identity") + colorscheme + coord_polar(theta="y") 
plot(p)

我得到以下信息:

忽略格式,我的问题是关于颜色选择。经理的颜色不匹配。区域图中的经理 A 颜色现在是经理 C 的颜色。我意识到这是因为饼图是按经理名称排序的,其中经理顺序为data未排序。

我无法控制接收数据的方式。有办法重新排序吗data and/or df(数据融化)以便第一个图表是按经理顺序排列的?或者改变数据发送到饼图的方式?

Thanks,


与其搞乱因子水平,不如子集化不是更容易吗df by the Date从最后一行开始data??

ggplot(df[df$Date==tail(data,1)$Date,],aes(x=1,y=value,fill=Manager)) + 
  geom_bar(stat="identity") + colorscheme + coord_polar(theta="y") 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ggplot中的数据顺序和颜色 的相关文章

随机推荐