我有以下資料框:
test = structure(list(Student = c("Ana", "Brenda", "Max", "Ana", "Brenda",
"Max", "Ana", "Brenda", "Max"), Month = structure(c(1L, 1L, 1L,
2L, 2L, 2L, 3L, 3L, 3L), .Label = c("January", "February", "March"
), class = "factor"), Grade = c(7L, 6L, 7L, 8L, 6L, 7L, 5L, 10L,
10L), Change = c("February", "February", "February", "February",
"February", "February", "February", "February", "February")), row.names = c(NA,
-9L), class = "data.frame")
我繪制了每個學生在幾個月內的成績,并想知道是否有一種簡單的方法可以突出每條繪制線的特定部分,該部分對應于顯示他們成績變化最大的時間段(此資訊是已經存在于資料集中:“更改”列。在這種情況下,對于所有學生來說,這將是從 2 月到 3 月)。
嘗試使用
我如何解決它?提前致謝!n_n
uj5u.com熱心網友回復:
不要在 aes 中指定大小。使用縮放功能
關于線路設計的另一個建議見下文。
test = structure(list(Student = c("Ana", "Brenda", "Max", "Ana", "Brenda",
"Max", "Ana", "Brenda", "Max"), Month = structure(c(1L, 1L, 1L,
2L, 2L, 2L, 3L, 3L, 3L), .Label = c("January", "February", "March"
), class = "factor"), Grade = c(7L, 6L, 7L, 8L, 6L, 7L, 5L, 10L,
10L), Change = c("Februrary", "Februrary", "Februrary", "Februrary",
"Februrary", "Februrary", "Februrary", "Februrary", "Februrary"
)), row.names = c(NA, -9L), class = "data.frame")
## typo corrected
test$Change <- "February"
library(ggplot2)
ggplot(test, aes(x = Month, y = Grade, color = Student, group = Student))
geom_point()
## don't specify size in aes
geom_line(data = test, aes(size = Month == Change))
## change the size scale
scale_size_manual(values = c(`TRUE` = 2, `FALSE` = .8))

另一種選擇可能是利用ggforce::geom_link在兩點之間插入美學的函式。
library(ggforce)
ggplot(test, aes(x = Month, y = Grade, color = Student, group = Student))
geom_point()
geom_link2(data = test, aes(size = Grade, ), lineend = "round")

嘗試更改線型時失敗。在這種情況下,請改用 geom_segment - 不過您需要進行一些資料轉換。
library(tidyverse)
test %>%
group_by(Student) %>%
mutate(xend = lead(Month), yend = lead(Grade)) %>%
ggplot(aes(x = Month, y = Grade, color = Student, group = Student))
geom_point()
geom_segment(aes(xend = xend, yend = yend, linetype = Month == Change))
# need to specify your x
scale_x_discrete(limits = unique(test$Month))
#> Warning: Removed 3 rows containing missing values (geom_segment).

uj5u.com熱心網友回復:
沿其路線更改線寬是可能的(正如 tjebo 指出的那樣),但它很少能畫出漂亮的圖。更清晰的方法可能是在感興趣的區域上添加彩色背景:
library(hrbrthemes)
library(ggplot2)
ggplot(test, aes(x = Month, y = Grade, color = Student, group = Student))
geom_point(alpha = 0)
geom_rect(data = test[1,],
aes(xmin = 'February', xmax = 'March', ymin = -Inf, ymax = Inf),
color = NA, fill = 'deepskyblue4', alpha = 0.1)
geom_line(size = 1)
geom_point(shape = 21, fill = 'white', size = 3)
theme_minimal()
scale_color_manual(values = c('pink3', 'orange2', 'red4'))
theme_tinyhand()

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444186.html
