首页 > 解决方案 > 如何将图形限制为仅显示正 x 轴上方的点?

问题描述

我目前的数据图如下所示:

我的数据图

然而,由于 2017 年左右出现负峰值,该图显示了 x 轴上方和下方的值。如何使图表仅显示 x 轴上方的值?

这是我目前用来生成图表的代码

plot(dandpw) addLegend(lty = 1)

我的数据 > head(dandpw) QLD1.Price NSW1.Price VIC1.Price SA1.Price TAS1.Price 2008-01-07 10:30:00 33.81019 36.52777 49.66935 216.45379 30.88968 2008-01-14 10:30:00 45.09321 37.55887 49.04155 248.33518 51.16057 2008-01-21 10:30:00 27.22551 29.57798 31.28935 31.56158 45.99226 2008-01-28 10:30:00 26.14283 27.32113 30.20470 31.90042 53.48170 2008-02-04 10:30:00 91.86961 36.77000 37.09027 37.57167 56.28464 2008-02-11 10:30:00 62.60607 28.83509 34.95866 35.18217 55.78961

输入(头(dandpw

标签: rplotxts

解决方案


您可以通过两种方式做到这一点。由于没有可用dput的(只有图片),我假设您的数据在数据框中。

  1. 您可以从数据集中删除负数
  2. 您可以在图表中显示的 y 轴上设置限制(使用ggplot2

方法1(不推荐,因为它会改变您的数据):

#remove negatives and replace with NA. Can also replace with 0 if desired
dandpw[dandpw < 0] <- NA

方法二:

#assume dandpw is data frame
library(tidyverse)
names(dandpw)[1] <- "date" #looks like your date column might not be named
#ggplot prefers long format
dandpw <- dandpw %>% gather(variables, values, -date)
ggplot(data = dandpw, aes(x = date, y = values, color = variables)) +
 geom_line() + 
 coord_cartesian(ylim = c(0, max(dandpw$values, na.rm = T) * 1.1 ))

推荐阅读