首页 > 解决方案 > 密度图 ggplot 错误返回缺失的美学错误

问题描述

我正在尝试为Density Plot数据框中四个波段中的每一个的类值绘制一个。现在,当我尝试绘制它时,geom_density返回一个错误。

我怎样才能解决这个问题?

Class   Red         Blue        Green       MSAVI
GRND    0.254241894 0.110313222 0.159854318 -0.216356573
SHRB    0.081104881 0.042177001 0.069155373 0.127747396
TREE    0.092559343 0.050581477 0.083049583 0.08810719
WATR    0.09050273  0.034529627 0.060246605 -0.182429743

dput(profiles)
structure(list(Class = structure(1:4, .Label = c("GRND", 
"SHRB", "TREE", "WATR"), class = "factor"), Red = c(0.254241893688838, 
0.081104880819718, 0.0925593425830205, 0.0905027302602927), Blue = c(0.110313221812248, 
0.0421770010143518, 0.050581476961573, 0.034529626990358), Green = c(0.159854317704837, 
0.0691553726792336, 0.0830495829383532, 0.0602466048051914), 
    MSAVI = c(-0.216356573005517, 0.12774739585196, 
    0.0881071899784729, -0.182429743309816)), row.names = c(NA, 
-4L), class = "data.frame")

代码

library(tidyverse)

# Read data
profiles = read.csv("~/profiles.csv")

# Make a DF
Profiles_df = as.data.frame(Profiles)

# Density Histograms
Profiles_df %>%  pivot_longer(
        cols = -"Class"
) %>% ggplot(
        mapping = aes(x = name, y = value, color = Class, group = Class)
) + 
  geom_density(alpha = 0.75) + 
  geom_vline(data = . %>% group_by(Class) %>% summarise(grp.mean = mean(value)),
             aes(x=grp.mean, color = Class), linetype="dashed", size=1) +
  scale_fill_manual(values=c('cyan', 'burlywood', 'darkgreen', 'blue'),
                    name = "class") +
  scale_color_manual(values=c("gray", "#CD853F", "#3CB371", "#33CEFF")) +
  theme(panel.background = element_blank(),
        panel.grid.major = element_line(color = "gray", size = 0.5),
        panel.grid.minor = element_line(color = "gray", size = 0.5),
        axis.ticks = element_blank()) +
  labs(x = "Value",
       y = "Density",
       title = "Density histograms of spectral profiles",
       subtitle = "Vertical lines represent mean group values")

错误

Error: geom_density requires the following missing aesthetics: x
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
Ignoring unknown aesthetics: x 

以下是我试图用我的数据生成的内容,请注意,由于数据不同,下图中的信息与我的数据不匹配。这只是提供一个想法。

在此处输入图像描述

标签: rggplot2

解决方案


看起来您想要 的密度图value,而不是name
尝试设置aes(x = value)andxintercept而不是xfor geom_vline

profiles %>% 
  pivot_longer(cols = -"Class") %>% 
  ggplot(aes(value, fill = Class, group = Class)) + 
  geom_density() + 
  geom_vline(data = . %>% group_by(Class) %>% summarise(grp.mean = mean(value)),
             aes(xintercept = grp.mean, color = Class), linetype="dashed", size=1) +
...

在此处输入图像描述


推荐阅读