ggplot:如何使用闪避位置绘制堆栈条形图

时间:2021-03-09 01:06:18

标签: r ggplot2

我有一个类似的数据集:

region country urban_rural treatment      potential
----------------------------------------------------
Africa  Kenya     1         chlorine       compatible
Europe  England   2         non_clorine    not compatible
Africa  Kenya     1         other          potential

我想画一个像:

enter image description here

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我希望我正确理解了您的问题。我制作了更多的虚拟数据行以获得更好的图。这些图表可以(并且可能应该)进一步完善。

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")

enter image description here

# 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)

enter image description here

相关问题