在R中使用ggplot为时间绘制多个值的折线图

时间:2018-08-06 09:56:01

标签: r ggplot2

我正在尝试使用ggplot(折线图)绘制随时间变化的几个城市的房价。 我融化了数据,使其看起来像:

Dates         variable       value  
2010-01-01    Shanghai       20435  
2010-02-01    Shanghai       20782  
...           Shanghai       ...  
2018-07-01    Shanghai       22491  
2010-01-01    Hangzhou       18827  
...           Hangzhou       ...  
2018-07-01    Hangzhou       29255  
...           ...            ...  

我的代码如下:

library(ggplot2)  
library(scales)  
library(reshape2)  
Housingpriceslong <- melt(Housingprices, id=c("Dates"))  
ggplot(Housingpriceslong, aes(x=Dates, y=value, colour=Housingpriceslong$variable)) + 
  geom_line() +
  scale_x_date(labels = date_format("%Y-%m"), breaks = date_breaks("6 months"))

我的问题是:

  1. 似乎有些错误,并且我没有正确的图形,请您帮我更正我的代码吗?
  2. scale_x_date函数也不执行任何操作,我的x轴比例仍然每年显示。

1 个答案:

答案 0 :(得分:0)

您的代码有(潜在)两个问题:

  1. 您需要确保Dates代表Date对象:将character向量或factoras.Date转换为Date向量。
  2. 请勿在{{1​​}}内使用$-索引:aes应该为colour=Housingpriceslong$variable)。

以下作品:

colour = variable

enter image description here


样本数据

library(tidyverse)
df %>%
    mutate(Dates = as.Date(Dates)) %>%
    ggplot(aes(Dates, value, colour = variable)) +
    geom_line() +
    scale_x_date(
        labels = scales::date_format("%Y-%m"),
        breaks = scales::date_breaks("6 months")) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))