如何在散点图中绘制不同的周末天数?
Posted
技术标签:
【中文标题】如何在散点图中绘制不同的周末天数?【英文标题】:How to plot the weekend days in a scatterplot as different? 【发布时间】:2021-03-06 08:04:30 【问题描述】:我有如下数据表(仅举例)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")
因此,我得到以下情节:
我想要一周内(周一至周五)的数据点,因为 points 代表(这里所有),周六和周日(也可能是国定假日)的数据点带有 十字/加/三角形代表。我该怎么做?
【问题讨论】:
我的建议是创建一个包含所有周末/假期的变量(例如weekends
),然后将形状美学映射到日期成员,即geom_point(aes(shape = date %in% weekends))
。您可以使用scale_shape_*()
函数控制精确的形状。
【参考方案1】:
尝试下一个方法为周末/工作日创建一个因子变量,并在geom_point()
中启用shape
选项:
#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))
输出:
【讨论】:
我有一个问题要问你:我可以强制周末天数为三角形,一周中的天数显示为一个点吗?如果我的数据表中的第一个条目是周末,那么周末就是点数,我不希望这样。以上是关于如何在散点图中绘制不同的周末天数?的主要内容,如果未能解决你的问题,请参考以下文章