r - ggplot 颜色条标签日期格式

标签 r ggplot2 date-formatting

是否可以将guide_colourbar上的数字标签格式化为日期格式,例如%b %Y?因此,Closing Date 图例上不再有 17400 17700 18000 18300,而是 %b %Y 等效项。

示例图

Example ggplot with guide_colourbar to format

用于生成绘图的代码

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))

enter image description here

关于r - ggplot 颜色条标签日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64397363/

相关文章:

r - 使用 caret 包找到 GBM 的最佳参数

r - 在 ggplot2 中的 x 轴标签下方添加图像

java - 将日期格式 yy/totaldaysinyear/totalsecondsinday 转换为 dd/mm/yyyy hh/mm/ss

java - 从 joda 时间到 java.time 的 `w` 符号格式不一致

scala - 将时间戳解析为 LocalDateTime Scala

r - 如何根据r中的日期/天拆分和制作新的csv文件?

java - 如何使用 rjava 在 R 中调用 String[][]

php - 是否有相当于 strtotime 的 R

r - facet_grid ggplot2 中显示更改单 margin ?

r - 如何增加ggplot2中分组条之间的空间?