I want to create a separate bar chart but only one bar appears and it looks like they add together, dodge doesn't work

28 Views Asked by At

I don't know why all the time the bar chart is not separated, I want to do a comparation between temperature and male-female floration monthly but dodge doesn't work.

enter image description here

year <- c("sep-2021", "oct-2021", "nov-2021", "dic-2021", "ene-2022", "feb-2022", "mar-2022", "abr-2022", "may-2022", "jun-2022", "jul-2022", "ago-2022", "sep-2022", "oct-2022")
temperature <- c(22, 22.2, 23.2, 22, 21.6, 22, 22, 22, 22, 22, 22, 22, 22, 22.4)
#precipitation <- c(461.8, 246.1, 225.8, 171.5, 343.1, 230.6, 429.9, 310.6, 414.7, 337.6, 433.7,306.3, 414.8, 377.3)
minflorescences<- c(12, 12, 60, 24, 40, 1, 0, 0,0,0 ,0, 0,0, 37)
finflorescences<- c(10, 17, 55, 30, 15, 8, 6, 0, 0, 0, 0, 0, 0, 10)
perf<- data.frame(year, temperature, minflorescences, finflorescences)
perf$year<- factor(perf$year,levels = unique(perf$year))
head(perf)

library(ggplot2)

ggplot(perf) +
  geom_col(aes(x= year, y=(minflorescences)) , position = position_dodge(width= 0.3), stat= "identity", fill="cyan", colour="#006000")+
  geom_col(aes(x= year, y=(finflorescences)), position = position_dodge(width= 0.3), stat= "identity", fill="magenta", colour="#006000")+
  geom_line(aes(x= year, y= temperature, group=2),stat = "identity",color="red", size=1)+
  labs(title = "Inflorescences temperature and precipitation",
       x="Date", y="Precipitation")+
  scale_y_continuous(sec.axis = sec_axis(~.*1,name = "Temperature °C"))+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
1

There are 1 best solutions below

1
On

You data isn't in the right shape. ggplot2 is build on the concept of tidy data. Hence, to achieve your desired result you have to reshape your data into tidy format using e.g. tidyr::pivot_longer:

library(ggplot2)
library(tidyr)

perf_tidy <- perf |>
  pivot_longer(c(minflorescences, finflorescences),
    names_to = "florescences",
    values_to = "value"
  )

ggplot(perf_tidy) +
  geom_col(
    aes(x = year, y = value, fill = florescences),
    position = "dodge",
    colour = "#006000"
  ) +
  scale_fill_manual(values = c("magenta", "cyan")) +
  geom_line(aes(x = year, y = temperature, group = 2), color = "red", size = 1) +
  labs(
    title = "Inflorescences temperature and precipitation",
    x = "Date", y = "Precipitation"
  ) +
  scale_y_continuous(sec.axis = sec_axis(~ . * 1, name = "Temperature °C")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.