gpt4 book ai didi

r - ggplot 和 R : Issue with barplot and the width of the bars when certain x values are missing

转载 作者:行者123 更新时间:2023-12-05 01:46:46 25 4
gpt4 key购买 nike

我有一个特定的数据集,显示了两家公司 4 年的销售收入。

year <- c(2009, 2011, 2012, 2009,2010, 2012)
name <- c('A', 'A', 'A', 'B', 'B', 'B')
sales <- c(500, 1000, 2000, 1500, 1000, 500)
df.t <- data.frame(year, name, sales)

输出:

> year name sales
> 2009 A 500
> 2011 A 1000
> 2012 A 2000
> 2009 B 1500
> 2010 B 1000
> 2012 B 500

请注意,A 公司没有 2010 年的销售数字(该年没有销售),而 B 公司没有 2011 年的销售数字。

我想创建一个漂亮的条形图来显示这些数字。

ggplot(data=df.t, aes(x=year, y=sales, fill=name)) + geom_bar(stat="identity", position="dodge")

但是,这会创建一个条形图,其中 2010 年和 2011 年的条形宽度与其他年份的条形宽度不同。

即使是没有销售的年份,我也想要一个条形图。该条形图的高度将为 0。

如何在不更改数据和添加零的情况下执行此操作?

最佳答案

I would like to have a bar chart even for the years with no sales. That barchart would have a height of 0. How can I do this without changing the data and adding zeros?

通常很难制作 ggplot 绘制不存在的数据。 @Thomas K 的答案中的 facet 选项有效,因为默认情况下 xy 比例在每个方面都是相同的,无论数据存在/不存在.但是,我认为添加零是最好的方法并且并不像您想象的那么难。只需添加零即可。 tidyr::complete 让它变得非常简单。

library(tidyr)
ggplot(complete(df.t, year, name, fill = list(sales = 0)),
aes(x=year, y=sales, fill=name)) +
geom_bar(stat="identity", position="dodge")

enter image description here

注意:这假定您的数据是这样的:

year <- c(2009, 2011, 2012, 2009,2010, 2012)
name <- c('A', 'A', 'A', 'B', 'B', 'B')
sales <- c(500, 1000, 2000, 1500, 1000, 500)
df.t <- data.frame(year, name, sales)

关于r - ggplot 和 R : Issue with barplot and the width of the bars when certain x values are missing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33613498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com