[英]ggplot: how to plot a stack bar plot with dodge position
我希望我正確理解了您的問題/問題。 我制作了更多的虛擬數據行以獲得更好的圖。 這些圖表可以(並且可能應該)進一步完善。
library(dplyr)
library(ggplot2)
library(data.table) # for the dummy data read in from plain text
# reading in some dummy data I made up buy copy and pasting plus minor changes
df <- data.table::fread("region,country,urban_rural,treatment,potential
Africa,Kenya,1,chlorine,compatible
Europe,England,2,non_clorine,not compatible
Africa,Kenya,1,other,potential
Africa,Kenya,1,chlorine,compatible
Africa,Kenya,2,non_clorine,not compatible
Europe,England,1,other,potential
Europe,England,1,other,potential
Europe,England,1,non_clorine,compatible
Africa,Kenya,2,non_clorine,not compatible
Africa,Kenya,1,non_clorine,potential
Africa,Kenya,1,other,potential
Europe,England,1,chlorine,compatible
Africa,Kenya,2,non_clorine,not compatible
Europe,England,1,other,potential
Africa,Kenya,1,other,potential
Africa,Kenya,1,non_clorine,compatible")
# one plot for Kenya with title and modified X axis label
df %>%
# build the counts to display in graph
dplyr::count(region, country, treatment, potential) %>%
# filter Kenya
dplyr::filter(country == 'Kenya') %>%
# plot
ggplot2::ggplot(aes(x = treatment, y = n, fill = potential )) +
ggplot2::geom_bar(stat="identity") +
# visual enhancement
ggplot2::ggtitle("Africa") +
ggplot2::xlab("Kenya")
# fast way to plot data for all countries
df %>%
# build the counts to display in graph
dplyr::count(region, country, treatment, potential) %>%
# plot
ggplot2::ggplot(aes(x = treatment, y = n, fill = potential )) +
ggplot2::geom_bar(stat="identity") +
# build the subplots from country variable
ggplot2::facet_wrap(~country)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.