如何在分组条形图上制作水平线,同时显示与每个组和图例对应的平均值?
How to make horizontal lines on a grouped bar chart that also display the average values corresponding to each group and the legends?
我的代码:
library(tidyverse)
library(lubridate)
library(ggplot2)
category <- c("apple", "apple", "apple","orange", "orange","orange")
mean_diameter_cm <- c(5.2,6.4,6.0, 9.2,8.6,8.1)
location <- c("Farm A","Farm B", "Farm C","Farm A","Farm B", "Farm C")
myfruit_data <- data.frame(category, mean_diameter_cm, location)
myfruit_data %>%
group_by(category, location) %>%
summarise(average_diameter = mean(mean_diameter_cm)) %>%
ggplot(aes(x=location, y=average_diameter, fill=category)) +
geom_col(position = "dodge")
我的条形图
我尝试手动计算每组的平均值,添加水平线和颜色,如下所示:
geom_line() +
geom_hline(yintercept = mean_diameter_cm,
color = c("green","red"))
这种方法的问题是我不知道如何手动添加相应的图例并显示平均值,即使我这样做了,对于一个不太复杂的任务来说似乎有点太复杂了,所以我我认为必须有一些我不知道的功能来完成更简单的方法,这就是我在这里问的原因。提前谢谢你。
也许这有帮助
library(dplyr)
library(ggplot2)
myfruit_data %>%
group_by(category) %>%
mutate(avg = mean(mean_diameter_cm)) %>%
ungroup %>%
mutate(colr = case_when(category == "apple" ~ "green",
TRUE ~ "red")) %>%
ggplot(aes(x=location, y=mean_diameter_cm, fill=category)) +
geom_col(position = "dodge") +
geom_line() +
geom_hline(aes(yintercept = avg, colour = colr)) +
guides(color = FALSE)
-输出
我有点不确定你想要什么,但也许是这个?
ggplot(myfruit_data, aes(x=location, y=mean_diameter_cm, fill = category)) +
geom_col(position = "dodge") + geom_hline(data = myfruit_data %>%
group_by(category) %>%
summarise_at(vars(mean_diameter_cm),
list(Mean = mean)), aes(yintercept = Mean, color = category))
我的代码:
library(tidyverse)
library(lubridate)
library(ggplot2)
category <- c("apple", "apple", "apple","orange", "orange","orange")
mean_diameter_cm <- c(5.2,6.4,6.0, 9.2,8.6,8.1)
location <- c("Farm A","Farm B", "Farm C","Farm A","Farm B", "Farm C")
myfruit_data <- data.frame(category, mean_diameter_cm, location)
myfruit_data %>%
group_by(category, location) %>%
summarise(average_diameter = mean(mean_diameter_cm)) %>%
ggplot(aes(x=location, y=average_diameter, fill=category)) +
geom_col(position = "dodge")
我的条形图
我尝试手动计算每组的平均值,添加水平线和颜色,如下所示:
geom_line() +
geom_hline(yintercept = mean_diameter_cm,
color = c("green","red"))
这种方法的问题是我不知道如何手动添加相应的图例并显示平均值,即使我这样做了,对于一个不太复杂的任务来说似乎有点太复杂了,所以我我认为必须有一些我不知道的功能来完成更简单的方法,这就是我在这里问的原因。提前谢谢你。
也许这有帮助
library(dplyr)
library(ggplot2)
myfruit_data %>%
group_by(category) %>%
mutate(avg = mean(mean_diameter_cm)) %>%
ungroup %>%
mutate(colr = case_when(category == "apple" ~ "green",
TRUE ~ "red")) %>%
ggplot(aes(x=location, y=mean_diameter_cm, fill=category)) +
geom_col(position = "dodge") +
geom_line() +
geom_hline(aes(yintercept = avg, colour = colr)) +
guides(color = FALSE)
-输出
我有点不确定你想要什么,但也许是这个?
ggplot(myfruit_data, aes(x=location, y=mean_diameter_cm, fill = category)) +
geom_col(position = "dodge") + geom_hline(data = myfruit_data %>%
group_by(category) %>%
summarise_at(vars(mean_diameter_cm),
list(Mean = mean)), aes(yintercept = Mean, color = category))