【问题标题】:100% Stacked bar Chart in RR中的100%堆积条形图
【发布时间】:2017-02-16 14:41:08
【问题描述】:

早安,

我试图在 R 中的 100% 堆积条形图中获取这些数据

        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

使它看起来像这样:

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

我尝试按照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")

任何帮助将不胜感激。

【问题讨论】:

  • 你应该添加你的代码,这样我们就可以看到出了什么问题。
  • “没用”到底是什么意思?请务必提供带有示例数据的reproducible example,以便我们可以实际运行代码以查看发生了什么。看起来我们的数据可能是错误的形状。

标签: r stacked-chart


【解决方案1】:

您需要融合您的数据。我稍微更改了您的数据以使其更易于加载,但这应该很容易替换。

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")

【讨论】:

  • 谢谢@Kristofersen。生成了一个图表,但它看起来与我在 Excel 中生成的快速图表非常不同。我似乎无法弄清楚发生了什么
  • @laura 有什么不同?你是指坐标轴和颜色吗?
  • @laura 抱歉,我有防火墙,所以无法查看任何图像。您必须描述需要更改的内容。不过这里有大量的 ggplot 示例,因此应该很容易弄清楚您要做什么。还有一个名为 ggthemeassist 的 rstudio 插件,它有助于 ggplot 设置。
  • @laura 您需要将您的数据换成我的数据,但列名相同,应该很容易。新图应该几乎完全相同。唯一的区别是颜色。
猜你喜欢
  • 2015-01-04
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 2013-12-19
相关资源
最近更新 更多