我有一个使用xtabs创建的数据框。
我的目标是使用这个数据框创建一个面积图/沙图,我只是不完全确定如何声明轴。
vg <- read.csv("vgdata.csv")
df <- data.frame(vg)
graph <- xtabs(Sales ~ Year + Genre, df)
print(graph)输出:
Genre
Year Action RPG Shooter
2005 3 2 2
2006 1 1 3
2007 3 3 4
2008 1 5 8
2009 4 7 7
2010 4 5 2通常我会使用销售、流派、年份等作为我的图的变量,但由于它是如何使用xtabs创建的,这些变量并不存在。我只是简单地将图作为定义的变量。
我希望在x轴上有年份,在y轴上有销售数据,流派是标签。我希望有一种简单的方法可以用我已经拥有的格式来做到这一点。我选择xtabs的原因是因为我每年都有几个视频游戏标题在动作、RPG和shooter下,这是一种方便的方法,可以将它们相加得到每年总销售额的数据帧。
发布于 2020-04-18 10:41:10
以下是几种绘制结果的可能方法。在这个例子中,我使用了你最后一个SO问题中的数据。
假设您按照所述方式使用xtabs:
result <- xtabs(Sales ~ Year + Genre, df)您可以转换为数据框:
plot_data <- as.data.frame(result)
plot_data
Year Genre Freq
1 2005 Action 3
2 2006 Action 0
3 2007 Action 1
4 2005 RPG 0
5 2006 RPG 4
6 2007 RPG 2
7 2005 Shooter 3
8 2006 Shooter 0
9 2007 Shooter 3对于面积图,可以将Year设为数字,而不是x轴上使用的系数:
plot_data$Year <- as.numeric(as.character(plot_data$Year))然后用geom_area绘图
library(ggplot2)
ggplot(plot_data, aes(x = Year, y = Freq, fill = Genre)) +
geom_area() +
scale_x_continuous(breaks = 2005:2007)Plot

Data
df <- structure(list(Name = 1:8, Year = c(2005L, 2005L, 2005L, 2006L,
2006L, 2007L, 2007L, 2007L), Genre = c("Action", "Action", "Shooter",
"RPG", "RPG", "Action", "Shooter", "RPG"), Sales = c(1L, 2L,
3L, 2L, 2L, 1L, 3L, 2L)), class = "data.frame", row.names = c(NA,
-8L))https://stackoverflow.com/questions/61260064
复制相似问题