首页 > 解决方案 > 如何在ggplot中使用已作为轴旋转的列的值

问题描述

我使用以下代码将area列和其他列旋转到列中 variable

fire_cat2 <- fire_cat %>% 
  pivot_longer(
    cols = colnames(fire_cat)[5:13],
    names_to = 'variable',
    values_to = 'value'
  )

我想绘制area值与其他“列”中的值之间的关系。当我运行以下代码时,R 输出Error in FUN(X[[i]], ...) : object 'area' not found

fire_cat2 %>% 
  ggplot(aes(x = value, y = area)) + 
  geom_point() +
  facet_wrap(vars(variable), scales = "free_x") +
  labs(
    title = "Relationships between other variables and area burned",
    x = "Value of colum",
    y = "Area burned (hectare)"
  )

解决方案表明这是一种正确的方法,所以我不确定它为什么不起作用。

*编辑 - 这是输出dput(head(fire_cat, 20))

structure(list(X = c(7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 6, 6, 
6, 6, 5, 8, 6, 6), Y = c(5, 4, 4, 6, 6, 6, 6, 6, 6, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 4, 4), month = structure(c(3L, 10L, 10L, 3L, 
3L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 8L, 9L, 9L, 9L, 3L, 10L, 3L, 
4L), .Label = c("jan", "feb", "mar", "apr", "may", "jun", "jul", 
"aug", "sep", "oct", "nov", "dec"), class = "factor"), day = structure(c(6L, 
3L, 7L, 6L, 1L, 1L, 2L, 2L, 3L, 7L, 7L, 7L, 6L, 2L, 4L, 6L, 7L, 
2L, 4L, 7L), .Label = c("sun", "mon", "tue", "wed", "thu", "fri", 
"sat"), class = "factor"), FFMC = c(86.2, 90.6, 90.6, 91.7, 89.3, 
92.3, 92.3, 91.5, 91, 92.5, 92.5, 92.8, 63.5, 90.9, 92.9, 93.3, 
91.7, 84.9, 89.2, 86.3), DMC = c(26.2, 35.4, 43.7, 33.3, 51.3, 
85.3, 88.9, 145.4, 129.5, 88, 88, 73.2, 70.8, 126.5, 133.3, 141.2, 
35.8, 32.8, 27.9, 27.4), DC = c(94.3, 669.1, 686.9, 77.5, 102.2, 
488, 495.6, 608.2, 692.6, 698.6, 698.6, 713, 665.3, 686.5, 699.6, 
713.9, 80.8, 664.2, 70.8, 97.1), ISI = c(5.1, 6.7, 6.7, 9, 9.6, 
14.7, 8.5, 10.7, 7, 7.1, 7.1, 22.6, 0.8, 7, 9.2, 13.9, 7.8, 3, 
6.3, 5.1), temp = c(8.2, 18, 14.6, 8.3, 11.4, 22.2, 24.1, 8, 
13.1, 22.8, 17.8, 19.3, 17, 21.3, 26.4, 22.9, 15.1, 16.7, 15.9, 
9.3), RH = c(51, 33, 33, 97, 99, 29, 27, 86, 63, 40, 51, 38, 
72, 42, 21, 44, 27, 47, 35, 44), wind = c(6.7, 0.9, 1.3, 4, 1.8, 
5.4, 3.1, 2.2, 5.4, 4, 7.2, 4, 6.7, 2.2, 4.5, 5.4, 5.4, 4.9, 
4, 4.5), rain = c(0, 0, 0, 0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0), area = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

标签: rdataframeggplot2

解决方案


主要错误是在透视列中包含第 13area列 。解决它并且代码有效。

library(dplyr)
library(tidyr)
library(ggplot2)

fire_cat %>%
  pivot_longer(cols = 5:12, names_to = "variable") %>% 
  ggplot(aes(x = value, y = area)) + 
  geom_point() +
  facet_wrap(~ variable, scales = "free_x") +
  labs(
    title = "Relationships between other variables and area burned",
    x = "Value of column",
    y = "Area burned (hectare)"
  )

推荐阅读