r - 条形和类别周围的边框,ggplot

标签 r ggplot2

我尝试在 ggplot 中绘制一个条形图,在 x 个国家/地区,每个物种的动物数量为 y。我做到了那么远,但是当我尝试勾勒出每个物种和条形图时,我得到了图中每个值之间的边界。

我还尝试使用 reprex 包来创建一个更好看的问题,包括我的图表,但我的声誉太低,无法发布图片。

所以我只尝试代码:

创建数据框

library(tidyverse)

country <- c( "AA", "AA", "BB", "BB", "CC", "CC", "DD", "DD", "EE", "EE")
sheep <-c(130, 146, 12, 15, 19, 0, 44, 57, 99, 123)
cattle <- c(11, 34, 221, 0, 91, 49, 33, 28, 19, 10)
pigs <- c(55, 0, 34, 48, 54, 0, 33, 59, 112, 23)

animals_wide <- data_frame(country, sheep, pigs, cattle)

“ reshape ” table 从宽到长(tidyr::gather)
animals_long <- animals_wide %>%
  gather(key = species, value = numbers, -country)

glimpse(animals_long)

由ggplot绘制
ggplot(animals_long, aes(country, numbers, fill = species)) +
  geom_bar(stat = "identity") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_fill_manual(values=c("gray", "black", "white"))

enter image description here

尝试通过添加 geom_bar(..., color = "black) 为 bar 中的“species”添加黑色轮廓
ggplot(animals_long, aes(country, numbers, fill = species)) +
  geom_bar(stat = "identity", color = "black") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_fill_manual(values=c("gray", "black", "white"))

enter image description here
所以,我想实现的是一个条形图,每个物种都有黑色边框。提前致谢!

最佳答案

该国家/地区在您的数据框中出现两次,因此每个物种有两个值。因此,您必须结合这两个值才能在您的绘图中获得一个黑色边框。

这很容易实现:

 animals_long <- animals_long %>% 
   group_by(country, species) %>% 
   summarise(numbers = sum(numbers))

这导致

enter image description here

关于r - 条形和类别周围的边框,ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52019721/

相关文章:

R列 split

r - 带误差线的散点图

从 R 中的 geojson 末尾删除括号 []

r - 如何创建图形和图像以在 R 中的同一面板上显示

r - ggbiplot - 改变点的大小

r - 将字符串拆分为数字和字符串(有缺失)

r - R中的重叠矩阵

r - 具有数据层的ggplot2刻面

r - ggplot2 热图缩放行

r - 使用 ggplot2、aes_string 和 reorder 制作绘图函数