R中的100%堆积条形图

时间:2017-02-16 14:41:09

标签: r stacked-chart

早上好,

我正在尝试将这些数据放在R

中的100%Stacked Bar图表中
        Federal Non Federal
2006    46753094    74740716
2007    43397314    74834857
2008    43962330    71051132
2009    42238038    72987898
2010    49546221    75232382
2011    48730233    76333479
2012    49316564    74669993
2013    48198329    75644892
2014    46630540    74783207
2015    46214781    75004771
2016    47625256    73744148

这样看起来像这样: enter image description here

我将是第一个承认它肯定不喜欢令人兴奋的地图的人,但它仍然需要。

我尝试按照here的说明执行代码,但它不起作用。

这就是我所做的:

>     g <- ggplot(FedNonFed, aes(FedNonFed))
>     g + geom_bar(aes(fill = FedNonFed), position = "fill")

不是我需要的图表。

g <- ggplot(FedNonFed, aes(FY))
g + geom_bar(aes(fill = FedNonFed), position = "fill")
g + geom_bar(aes(fill = TotalExpense), position = "fill")

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:7)

您需要融化数据。我稍微更改了一些数据,以便更容易加载,但这应该很容易替换。

library(reshape2)
library(scales)
df = data.frame("Year" = seq(2006,2016,by = 1), "Federal" = seq(1,11,by = 1), "Non Federal" = seq(11,1,by = -1))
dfm = melt(df, id.vars = "Year")
ggplot(dfm,aes(x = Year, y = value,fill = variable)) + 
  geom_bar(position = "fill",stat = "identity") + 
  scale_y_continuous(labels = percent_format())

我对情节进行了一些更改,因此它更接近于excel情节。唯一不同的是颜色。

ggplot(dfm,aes(x = Year, y = value,fill = variable)) + 
  geom_bar(position = "fill",stat = "identity") + 
  scale_y_continuous(labels = percent_format())+ scale_x_continuous(breaks = 2006:2016,labels= as.character(seq(2006,2016,by = 1)))+
  theme(plot.subtitle = element_text(vjust = 1), 
    plot.caption = element_text(vjust = 1), 
    legend.title = element_blank(), 
    axis.title.x=element_blank(),
    axis.title.y=element_blank(),
    legend.position = "bottom", legend.direction = "horizontal")