如何在R中使用ggplot2正确创建此条形图?

3z6pesqy  于 2023-03-15  发布在  其他
关注(0)|答案(2)|浏览(156)

示例数据如下:

library(tidyverse)
df=tibble(type=c('grass','forest','desert','crop'),
          temperature=c(0.6206,0.6132,0.6235,0.6134),
          precipitation=c(252,290,198,337),
          radiation=c(156,177,123,205))
dff <- df %>% pivot_longer(cols = -type,
                           names_to = 'n',
                           values_to = 'v')
dff
ggplot(data = dff)+
  geom_bar(aes(x=type,y=v,
               fill=n),
           stat = 'identity',
           position = 'dodge')

问题是“温度”变量太低,无法观察到它!!!我如何才能做出更好的数字?提前感谢!

wwtsj6pe

wwtsj6pe1#

我同意这里的评论。你有三个不同维度的不同变量,它们根本不应该用相同的比例绘制。虽然你 * 可以 * 添加第二个轴,但如果你用x,y和颜色美学在一个图上表示温度,降水和辐射这三个不同维度,可能会更容易,更直观,更容易理解。

ggplot(df, aes(temperature, precipitation, fill = radiation)) +
  geom_point(shape = 21, size = 10, color = 'white', alpha = 0.5) +
  geom_point(shape = 21, size = 5, color = 'white') +
  geom_text(aes(label = type), position = position_nudge(0.001, 10)) +
  scale_fill_viridis_c(option = 'C') + 
  theme_minimal(base_size = 20) +
  xlim(0.61, 0.63) +
  coord_cartesian(clip = 'off') +
  theme(panel.border = element_rect(fill = NA, color = 'gray80',
                                    linewidth = 0.5),
        panel.grid = element_line(linewidth = 0.4),
        panel.grid.minor.x = element_blank())

7xzttuei

7xzttuei2#

这里是一个建议使用两个y轴。也不是理想的解决方案:

library(tidyverse)

df %>% 
  mutate(space = NA) %>% 
  mutate(temperature = temperature*100) %>% 
  pivot_longer(cols = -type,
                           names_to = 'n',
                           values_to = 'v') %>% 
  ggplot(aes(x=type,y=v,fill=n))+
  geom_col(position = position_dodge())+
  scale_fill_manual(values = c("blue", "red", "NA", "purple"),
                    limits = c("precipitation","radiation","","temperature")) +
  scale_y_continuous(
    name = "Precipitation & Radiation",
    sec.axis = sec_axis(~.*0.01, name = "Temp")
  )+
  xlab("\nType")+
  theme_bw(14)+
  theme(
    axis.title.y = element_text(color = "grey", size=13, face="bold"),
    axis.title.y.right = element_text(color = "purple", size=13, face="bold"),
    axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1)
  )

相关问题