r - ggplot:在线条图中标记 x 轴
问题描述
很长一段时间以来,我都绝望地在我的绘图(ggplot2)中拉直 x 轴的标签。挑战在于我有两个 geom_paths,每个都从不同的数据帧中获取数据 - 我相信这在代码中会变得更加清晰:
ggplot(data=dx, aes(x = year, y=en.x ))+
scale_y_continuous(breaks = scales::pretty_breaks(n = 2))+
geom_path(data=ps, aes(x, y, color = "Person 1", linetype="Person 1"), size=0.5)+
geom_path(data=pg, aes(x , y, color = "Person 2", linetype="Person 2"), size=0.5)+
scale_color_manual("",labels = c(Nutzer1, Nutzer2), values = c("Person 1" = Nutzer1Farbe, "Person 2" = Nutzer2Farbe)) +
scale_linetype_manual("",labels = c(Nutzer1, Nutzer2), values=c("Person 1"=Nutzer1Format, "Person 2"=Nutzer2Format))
目标是用数据框“dx”中的年份标记 X 轴,如 aes 参数所示。它有效!但仅当您禁用 geom_paths - 如下所示:
ggplot(data=dx, aes(x = year, y=en.x ))+
scale_y_continuous(breaks = scales::pretty_breaks(n = 2))+
#geom_path(data=ps, aes(x, y, color = "Person 1", linetype="Person 1"), size=0.5)+
#geom_path(data=pg, aes(x , y, color = "Person 2", linetype="Person 2"), size=0.5)+
scale_color_manual("",labels = c(Nutzer1, Nutzer2), values = c("Person 1" = Nutzer1Farbe, "Person 2" = Nutzer2Farbe)) +
scale_linetype_manual("",labels = c(Nutzer1, Nutzer2), values=c("Person 1"=Nutzer1Format, "Person 2"=Nutzer2Format))
我真的不明白为什么路径会像这样破坏标签 - 它必须是 aes 参数。
如果有人对此有解决方案,我将非常感激!
解决方案
这可以像这样实现:
- 在调用之前将您的原始月份变量转换为日期时间
xspline
。这样,插值日期值可以很容易地通过例如转换回日期时间lubridate::as_datetime
。 - 除此之外,您可以对数据集进行行绑定,这使得绘图更容易
library(ggplot2)
library(tidyr)
library(dplyr)
datengesamt <- datengesamt %>%
# Convert to datetime
mutate(month = as.POSIXct(month))
plot(1, 1)
ps <- xspline(datengesamt[,1], datengesamt[,2], 1, draw=FALSE)
pg <- xspline(datengesamt[,1], datengesamt[,3], 1, draw=FALSE)
pp <- list("Person 1" = data.frame(ps), "Person 2" = data.frame(pg)) %>%
bind_rows(.id = "id") %>%
mutate(x = lubridate::as_datetime(x))
ggplot(pp, aes(x, y, color = id, linetype = id)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 2)) +
geom_path(size=0.5) +
scale_x_datetime(date_labels = "%Y")
推荐阅读
- python - 如何将多个对象添加到场景中?
- python - 如何在 pandas 数据框中一次更改多个值,使用数组作为长度不同的索引?
- elasticsearch - 使用弹性搜索进行交易
- java - 使用动态字符串来引用arraylist
- android - Dagger 看不到我自己生成的依赖
- java - javax.net.ssl.SSLHandshakeException:收到致命警报:handshake_failure(使用 Rest API,Oracle 云中的 JDK 7)
- laravel - 如何在 Laravel 中使用“LIKE”条件搜索两个表
- tfs - 使用相同 SQL Server 进行 Azure DevOps 迁移
- ios - 修复触摸在 UITableViewCell 内的 UILabel 上不起作用?
- java - 为什么程序显示空结果?