条形图和类别的边框,ggplot

4
我尝试在ggplot中绘制一个条形图,y轴是每个物种的动物数量,x轴是国家。我已经成功绘制了图表,但是当我尝试勾勒出每个物种和条形时,就会在图表中每个值之间得到边框。
我还尝试使用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)

animals_long <- animals_wide %>%
  gather(key = species, value = numbers, -country)

glimpse(animals_long)

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

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

在此输入图像描述

因此,我想实现的是每个物种都有黑色边框的条形图。提前感谢!

现在你应该能够发布图片了。 - Sal-laS
如果您仍无法上传图像,请将其上传到网络中的其他空间,并在问题中添加链接。 - Sal-laS
1个回答

4

在您的数据框中,同一国家出现了两次,因此每个物种有两个值。因此,您需要组合这两个值,以获得绘图中的一个黑色边框。

这很容易实现:


```R ggplot(data = df, aes(x = species, y = value, fill = country)) + geom_col(position = "dodge", color = "black") ```
 animals_long <- animals_long %>% 
   group_by(country, species) %>% 
   summarise(numbers = sum(numbers))

这会导致:

图片描述在此输入


谢谢,我漏掉了总结!完美。 - LErnholm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接