首页 > 解决方案 > 希望 nondetects 显示在 ggplot 图上

问题描述

我希望我的未检测结果显示在我的图表上(因此它看起来不仅仅是在特定日期的特定位置没有收集到任何数据)。我想把它们做成三角形?我不确定我的 csv 设置是否正确,或者我是否使用了正确的命令。我很欣赏任何见解。

注意:我将 0 放在未检测到的“结果”列中,在“检测”列中,我将 1 分配给所有检测到,将 0 分配给所有未检测到。我认为这可能是我的问题的一部分 - 但我不知道如何解决它......这是我的代码:

示例数据

Date       Reservoir           Result    Detects
9/24/2019  Epilimnion          0.2       1
9/24/2019  Metalimnion         0.6       1
9/24/2019  Hypolimnion         1.8       1
10/8/2019  Epilimnion          0         0
10/8/2019  Metalimnion         1.9       1
10/8/2019  Hypolimnion         3.7       1
10/22/2019  Epilimnion         0         0
10/22/2019  Metalimnion        0         0
10/22/2019  Hypolimnion        2.7       1

    TN<-read.csv("TN.csv", header=TRUE)
    library(lubridate)
    library(ggplot2)
    library(scales)
ggplot(TN, aes(x = mdy(Date), y = Result, color = Reservoir, pch=ifelse(Detects, 19, 17), cex = 1.5))+
  geom_point(size = 4)+
  ylab("Total Nitrogen (mg/L)") +
  scale_x_date(name = "", breaks = date_breaks("1 month"), labels = date_format("%b %Y"), 
               limits = c(mdy("08/30/2019"),mdy("1/10/2020"))) + 
  scale_color_discrete(labels = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion"),
                       breaks = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion")) +
  theme(legend.position="bottom", legend.text=element_text(size=12, face="bold"),
        axis.text.x = element_text(angle = 45, vjust = 1.0, hjust = 1.0, size=12,), axis.text.y = element_text(size=12), axis.title.y = element_text(vjust=3, size=12, face="bold"),
        legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5))

标签: rggplot2

解决方案


该错误信息丰富:

Error: A continuous variable can not be mapped to shape

其中指的是 pch 参数:

pch=ifelse(Detects, 19, 17)

正如 MrFlick 所提到的,这就是 ggplot 所说的 a shape。数字 19 和 17 在人眼看来可能是离散的,但对于计算机(在本例中为 R)它们实际上是连续的(=数字)。ggplot 意义上的离散意味着分类(=因子)。所以,把这个变量变成一个因子,直接用它作为shape参数(顺便说一句pch也可以),鲍勃是你的叔叔:

TN %>%
  mutate(Detects=factor(Detects)) %>%
  ggplot(aes(x = mdy(Date), y = Result, color = Reservoir, pch=Detects), size = 1.5) +
  geom_point(size = 4)+
  ylab("Total Nitrogen (mg/L)") +
  scale_x_date(name = "", breaks = date_breaks("1 month"), labels = date_format("%b %Y"), 
               limits = c(mdy("08/30/2019"),mdy("1/10/2020"))) + 
  #scale_color_discrete(labels = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion"),
  #                     breaks = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion")) +
  theme(legend.position="bottom", legend.text=element_text(size=12, face="bold"),
        axis.text.x = element_text(angle = 45, vjust = 1.0, hjust = 1.0, size=12,), 
        axis.text.y = element_text(size=12), axis.title.y = element_text(vjust=3, size=12, face="bold"),
  #      legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5)) 

在此处输入图像描述 请注意,我删除了您的scale_color_discrete覆盖,我建议不要隐藏图例标题。


推荐阅读