我正在尝试使用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"))
我的问题是:
scale_x_date
函数也不执行任何操作,我的x轴比例仍然每年显示。答案 0 :(得分:0)
您的代码有(潜在)两个问题:
Dates
代表Date
对象:将character
向量或factor
与as.Date
转换为Date
向量。$
-索引:aes
应该为colour=Housingpriceslong$variable
)。 以下作品:
colour = variable
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))