r - 如何在散点图中绘制不同的周末天数?
问题描述
我有以下数据表(仅作为示例)dt.data
:
dt.data <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
DE = rnorm(365, 4, 1), AT = rnorm(365, 10, 2),
IT = rnorm(365, 1, 2), check.names = FALSE)
# Add nr-column for different colored points: #
dt.data$nr <- sort(rep(1:7, length.out = nrow(dt.data)))
## PLOT: ##
p <- ggplot(data = dt.data, aes(x = AT, y = DE, color = as.factor(nr),
text = paste("Date: ", date, '\n',
"AT: ", AT, "GWh/h", '\n',
"DE: ", DE, "\u20ac/MWh"),
group = 1)
) +
geom_point() +
scale_color_manual(values = colorRampPalette(brewer.pal(n = 8, name = "Greens")[4:8])( length(unique(dt.allData$nr)) )) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
xlab("AT") +
ylab("DE")
# Correlation plot converting from ggplot to plotly: #
scatterPlot <- plotly::ggplotly(p, tooltip = "text")
因此,我得到以下情节:
我想要一周内的数据点(周一到周五),因为点代表(这里所有),周六和周日的数据点(也可能是国定假日)用十字/加号/三角形表示。我怎样才能做到这一点?
解决方案
尝试以下一种方式为周末/工作日创建一个因子变量,并启用以下shape
选项geom_point()
:
#Create day of week
dt.data$Day <- as.numeric(weekdays(dt.data$date) %in% c('Saturday','Sunday'))
dt.data$Day <- factor(dt.data$Day,levels = c(1,0),labels = c('Weekend','Weekday'))
## PLOT: ##
p <- ggplot(data = dt.data, aes(x = AT, y = DE, color = as.factor(nr),
text = paste("Date: ", date, '\n',
"AT: ", AT, "GWh/h", '\n',
"DE: ", DE, "\u20ac/MWh"),
group = 1)) +
geom_point(aes(shape=Day)) +
scale_color_manual(values = colorRampPalette(brewer.pal(n = 8, name = "Greens")[4:8])(length(unique(dt.data$nr)))) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
xlab("AT") +
ylab("DE")
# Correlation plot converting from ggplot to plotly: #
scatterPlot <- plotly::ggplotly(p, tooltip = "text")
输出将是:
或遵循@teunbrand的明智建议:
## PLOT 2
ggplot(data = dt.data, aes(x = AT, y = DE, color = as.factor(nr),
text = paste("Date: ", date, '\n',
"AT: ", AT, "GWh/h", '\n',
"DE: ", DE, "\u20ac/MWh"),
group = 1)) +
geom_point(aes(shape=Day)) +
scale_color_manual(values = colorRampPalette(brewer.pal(n = 8, name = "Greens")[4:8])(length(unique(dt.data$nr)))) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
xlab("AT") +
ylab("DE") +
scale_shape_manual(values = c('Weekend'=1,'Weekday'=3))
输出:
推荐阅读
- javalite - Javalite for Microservice 项目,是否提供应用程序跟踪/监控支持?
- python - Python Selenium - 尝试/排除不起作用
- laravel - 将父模型的数据提取到 static::saving() 启动函数中
- azure-devops - 发布成功后触发发布
- javascript - 根据首先返回的异步调用执行函数
- java - 如何查找是否在会话中添加或删除了所有数据?
- bash - 如果目标失败,Makefile 应该退出
- vb.net - VB替换列表中的对象
- wordpress - 强制在 SSL / HTTPS 中安装 WordPress
- python - 未使用 sys 模块的 Python 模块导入错误