【问题标题】:Plot the Average Value of a Variable using ggplot2使用 ggplot2 绘制变量的平均值
【发布时间】:2020-04-18 18:53:59
【问题描述】:

我想在条形图中绘制两列:“Property_type”和“Price”。 使用下面的代码,我将为每种房产类型绘制“总价”而不是“中位价”。 你能帮我修复代码吗?

theme_set(theme_bw())

# Draw plot
ggplot(data, aes(x=Property_type, y=Price)) + 
  geom_bar(stat="identity", width=.5, fill="tomato3") + 
  labs(title="Ordered Bar Chart", 
       subtitle="Average Price by each Property Type", 
       caption="Image: 5") + 
  theme(axis.text.x = element_text(angle=65, vjust=0.6))

【问题讨论】:

  • 在绘图前简单聚合:ggplot(aggregate(Price ~ Property_type, data, FUN=median), ...

标签: r ggplot2 data-visualization median


【解决方案1】:

使用dplyr,您可以计算每个房产的中位数价格,然后将这个新变量作为y 值传递给ggplot2

library(dplyr)
library(ggplot2)

data %>% 
  group_by(Property) %>% 
  summarise(MedPrice = median(Price, na.rm = TRUE)) %>%
  ggplot(aes(x = reorder(Property,-MedPrice), y = MedPrice)) +
  geom_col(fill = "tomato3", width = 0.5)+
  labs(title="Ordered Bar Chart", 
       subtitle="Average Price by each Property Type", 
       caption="Image: 5") + 
  theme(axis.text.x = element_text(angle=65, vjust=0.6))

它回答了你的问题吗?

如果不是,请按照本指南提供可重现的数据集示例:How to make a great R reproducible example

【讨论】:

  • 非常感谢!只是一个简单的问题:我知道有中间价,但是这些条不是从中间价最高的条中排序到最低的。你能指导我吗?
  • 不客气 ;) 我编辑了我的答案,以根据它们在绘图上的中值价格重新排序条形图。让我知道是否可以。如果没有,请在您的问题中提供一个可重复的示例
【解决方案2】:

虽然 dc37 的答案可以完美地满足您的需求,但我只想指出,您还可以使用 ggplot 中的 stat_* 系列函数来计算分组汇总统计数据。

library(ggplot2)

df <- data.frame(
  Property = rep(LETTERS[1:10], each = 10),
  Price = rnorm(100, rep(1:10, each = 10))
)

ggplot(df, aes(Property, Price)) +
  stat_summary(fun = median, geom = "col")

reprex package (v0.3.0) 于 2020-04-18 创建

【讨论】:

  • 好点 ;) 由于某些原因,我不记得使用 stat_summary 来解决这类问题。
  • 我最近也开始采用更多的stat家族,可以很方便。
猜你喜欢
  • 2021-08-28
  • 1970-01-01
  • 2015-07-22
  • 2019-07-24
  • 2020-05-02
  • 2017-04-25
相关资源
最近更新 更多