LErnholm
LErnholm

Reputation: 75

Border around bars and caterories, ggplot

I try to plot a bar plot in ggplot, having as y number of animals per species by on x the countries. I manage that far, but as I try to outline each species and bar I get the border between each value in the graph.

I also tried using the reprex package to create a nicer looking question including my graphs, but I have too little reputation to post the pictures apparently.

So I try the code only:

create dataframe
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' the table from wide to long (tidyr::gather)
animals_long <- animals_wide %>%
  gather(key = species, value = numbers, -country)

glimpse(animals_long)
plot by 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

tries to add black outline to 'species' in bar by adding geom_bar(..., colour = "black)
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 So, what I would like to achieve is a bar plot with a black border of each of the species. Thanks in advance!

Upvotes: 4

Views: 10641

Answers (1)

Stephan
Stephan

Reputation: 2246

the country appears twice in your data frame, hence two values for each species. therefor, you have to combine both values to get one black border in your plot.

thats easy achieveable with:

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

which leads to

enter image description here

Upvotes: 4

Related Questions