是否可以将guide_colourbar上的数字标签格式化为日期格式,例如%b %Y
?因此,Closing Date
图例上不再有 17400 17700 18000 18300
,而是 %b %Y
等效项。
示例图
用于生成绘图的代码
Area = c(1705, 902, 1496, 1257, 763)
ClosePrice = c(2292500, 977520, 1990680, 1720840, 855330)
HasTerrace = c(FALSE, FALSE, TRUE, FALSE, TRUE)
CloseDate = as.Date(c('2017-03-17', '2017-02-28', '2018-05-09', '2020-03-01',
'2017-01-09'))
data <- data.frame(Area, ClosePrice, HasTerrace, CloseDate)
data %>%
ggplot(aes(x=Area, y=ClosePrice, shape=HasTerrace)) +
geom_point(aes(colour=CloseDate), size=3, alpha=0.8) +
scale_color_viridis() +
theme_minimal() +
scale_x_continuous(expression(Indoor~Area~(ft^2)),
labels=label_comma()) +
scale_y_continuous('Closing Price ($m)',
labels=label_number(accuracy=0.01, scale=10^-6)) +
theme(legend.position='bottom', legend.box='vertical') +
guides(shape = guide_legend(title='Has a Terrace'),
colour = guide_colourbar(title='Closing Date',
barwidth=10,
labels=label_date(format='%b %Y')))
最佳答案
这里有一个解决方案。 guide_colorbar()
函数不接受 labels
参数,因此会忽略它。您需要将标签添加到 scale_color_viridis
。但是,除非您还包含 trans = "date"
,否则这会产生错误。
data %>%
ggplot(aes(x=Area, y=ClosePrice, shape=HasTerrace)) +
geom_point(aes(colour=CloseDate), size=3, alpha=0.8) +
scale_color_viridis(name='Closing Date',
trans = "date",
labels = label_date(format = "%b %Y") )+
theme_minimal() +
scale_x_continuous(expression(Indoor~Area~(ft^2)),
labels=label_comma()) +
scale_y_continuous('Closing Price ($m)',
labels=label_number(accuracy=0.01, scale=10^-6)) +
theme(legend.position='bottom', legend.box='vertical') +
guides(shape = guide_legend(title='Has a Terrace'),
colour = guide_colourbar(barwidth=10))
关于r - ggplot 颜色条标签日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64397363/