Home > Blockchain >  Changing color of bins in ggplot2 histograms
Changing color of bins in ggplot2 histograms

Time:04-02

I am trying to change the color of the bins, based on group, of one of the ggplot histograms. I see the outline of the bins is specified in geom_histogram(color="black") but am not sure how to change the fill color of the bins themselves.

Below is the code:

ggplot(
  Size_Comparison_Proper_Without_Juveniles\_, 
  aes(x=values, fill=group)
  )  
geom_histogram(
  position="dodge", 
  alpha = 1, 
  bins=30,
  color="black") 
labs(
  title='Total Length at Earthworm Sites \\n vs Total Length at Earthworm-Free Sites',
  y='Count',
  x='Snout-Vent Length (mm)') 
theme(
  legend.position="top",
  text = element_text(size=15)) 
scale_fill_discrete(
    name="Group", 
    labels=c("With Earthworms - Total Length","Without Earthworms - Total Length")) 
geom_vline(
    xintercept=38.39, 
    color="royalblue4",
    size=1.5,
    linetype="longdash") 
geom_vline(
    xintercept=39.62583,
    color="orange", 
    size=1.5,
    linetype="longdash")

Thank you!!

enter image description here

I have only tried playing around aes(color="") and geom_histogram(color="")

    structure(list(EW = c(34, 42, 34, 34, 34, 39), noEW = c(36, 35, 
39, 35, 36, 38), values = c(34, 42, 34, 34, 34, 39), group = c("Tot_ew", 
"Tot_ew", "Tot_ew", "Tot_ew", "Tot_ew", "Tot_ew")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

CodePudding user response:

As @Bloxx pointed out, you can use scale_fill_manual. However, you don't need both, so we can replace the other scale_fill_discrete.

library(tidyverse)

ggplot(df,
       aes(x = values, fill = group))  
  geom_histogram(position = "dodge", alpha = 1, bins = 30, color = "black")  
  labs(title = 'Total Length at Earthworm Sites \\n vs Total Length at Earthworm-Free Sites',
       y = 'Count',
       x = 'Snout-Vent Length (mm)')  
  theme(legend.position = "top",
        text = element_text(size = 15))  
  scale_fill_manual(
    name = "Group",
    labels = c(
      "With Earthworms - Total Length",
      "Without Earthworms - Total Length"
    ),
    values = c("dark blue", "light blue")
  )  
  geom_vline(xintercept = 38.39, color = "royalblue4", size = 1.5, linetype = "longdash")  
  geom_vline(xintercept = 39.62583, color = "orange", size = 1.5, linetype = "longdash")

Output

enter image description here

Data

df <- structure(list(EW = c(34, 42, 34, 34, 34, 39, 35, 36, 37, 38, 
40), noEW = c(36, 35, 39, 35, 36, 38, 35, 36, 37, 38, 40), values = c(34, 
42, 34, 34, 34, 39, 35, 36, 37, 38, 40), group = c("Tot_ew", 
"Tot_ew", "Tot_ew", "Tot_woew", "Tot_woew", "Tot_woew", "Tot_ew", 
"Tot_ew", "Tot_ew", "Tot_woew", "Tot_woew")), row.names = c(NA, 
-11L), class = c("tbl_df", "tbl", "data.frame"))
  • Related