我想创建一个单独的条形图,但只出现一个条形图,而且看起来它们加在一起,闪避不起作用

问题描述 投票:0回答:1

不知道为什么条形图一直不分开,我想每月做一下温度和男女花期的比较,但是闪避不行。

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))
r ggplot2 stat position-dodge
1个回答
0
投票

您的数据形状不正确。

ggplot2
建立在整洁数据的概念之上。因此,为了达到您想要的结果,您必须使用例如将数据重塑为整齐的格式。
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.

© www.soinside.com 2019 - 2024. All rights reserved.