使用 ggplot2 绘制变量的平均值
Plot the Average Value of a Variable using ggplot2
我想在条形图中绘制两列:"Property_type" 和 "Price"。
使用下面的代码,我将为每个 属性 类型绘制 "total price" 而不是 "median 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))
使用 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
虽然 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 创建
我想在条形图中绘制两列:"Property_type" 和 "Price"。 使用下面的代码,我将为每个 属性 类型绘制 "total price" 而不是 "median 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))
使用 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
虽然 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 创建