【问题标题】:100 % stacked area plot in ggplot2ggplot2 中的 100 % 堆积面积图
【发布时间】:2016-03-18 14:55:54
【问题描述】:

this 问题的启发,我想创建一个 100% 堆叠面积图,其中 ggplot2 按国家/地区排序的年份显示电影。我的数据框可以检索到here。我有两个变量yearcountry。我知道我的想法是否有错误,但我无法得到解决方案。

我使用的代码是:

library(reshape)
library(ggplot2)

df <- read.csv(url("https://dl.dropboxusercontent.com/u/109495328/movie_db.csv"))
ggplot(df, aes(x=Year,y=Country,group=Country,fill=Country)) + geom_area(position="fill")

我的图表如下所示:

但应该看起来像这样(示例图):

我错过了什么?

编辑:

Axeman,我不明白您是如何获得 Freq 变量的,即使您使用了更新的解决方案?

我不确定这是否有必要,或者ggplot 是否正在“自动”执行此操作,但我认为我遇到的实际问题是将上面的数据框转换为数据框,了解一个国家/地区每年出现的频率并保存它频率:

发件人:

year country
2015 US
2015 US
2014 UK
2015 UK
2014 US
.
.
.

收件人:

year country freq
2015 US      6
2015 UK      7
2014 US      10
2014 UK      2

【问题讨论】:

  • 您没有很好地解释图表应该显示的内容。您的示例有一个连续的 y 轴,您的代码有一个因子为 y。还要检查range(df$Year)
  • geom_area 中使用stat = "identity"position = "stack" 有帮助吗?见here for an example
  • @Jaap,它不起作用。它看起来类似于我在上面显示的图形输出。 @ Axeman,我想显示与制作它们的国家相比,数据框中每年有多少部电影。我觉得我必须添加第三个变量,每行只显示1。 Axeman,你有什么建议?

标签: r csv ggplot2


【解决方案1】:

仍然有点不确定你想要什么,但这是我的尝试:

#load some libraries
library(dplyr)
library(tidyr)

#get rid of some clear errors in your supplied data
df <- filter(df, Country != '')
df <- droplevels(df)

#now pre-calculate the proportion for each country each year summing up to one.
#note that it may be more useful to have actual counts here instead of 0 or 1.
df2 <- table(Year = df$Year, Country = df$Country) %>% prop.table(1) %>% as.data.frame()
#fix year into a numeric
df2$Year <- as.numeric(as.character(df2$Year))

#make the plot
ggplot(df2, aes(x=Year,y=Freq,group=Country,fill=Country)) + 
  geom_area(alpha = 1) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))

如果您不希望它们总和为 1,请改用:

df3 <- table(Year = df$Year, Country = df$Country) %>% as.data.frame()
#fix year into a numeric
df3$Year <- as.numeric(as.character(df3$Year))

#make the plot
ggplot(df3, aes(x=Year,y=Freq,group=Country,fill=Country)) + 
  geom_area(alpha = 1) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))

【讨论】:

  • Axeman,非常感谢您的尝试!我们非常接近!我发现了我的错误:它不是 100% 面积图,而是“只是”一个面积图(我相应地调整了标题)。 y 轴假设显示每年电影的总和。例如,在 2015 年的所有电影中,假设有 100 部电影应该在那里放映。然而,对于 2014 年,只有 50 个。因此 2014 年应指示 50 个。我认为 ggplot 检索数字,即。 e. 2015 年为 100,2014 年为 50,通过读取 2015 在数据框中出现的次数并将其保存在您称为 Freq 的变量中。我怎样才能做到这一点?
  • 对,对不起,你的示例图片让我失望了。我想你想改用这条线:df2 &lt;- table(Year = df$Year, Country = df$Country) %&gt;% as.data.frame()(没有prop.table)。
  • Axeman,非常感谢您的回复。请注意我上面的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-10
  • 2013-05-28
  • 1970-01-01
相关资源
最近更新 更多