我有以下資料:
structure(list(Month = c("2018-08", "2018-09", "2018-10", "2018-11",
"2018-12", "2019-01", "2019-02", "2019-03", "2019-04", "2019-05",
"2019-06", "2019-07", "2019-08", "2019-09", "2019-10", "2019-11",
"2019-12", "2020-01", "2020-02", "2020-03", "2020-04", "2020-05"
), `Member 1` = c("Yes", "Yes", "Yes", "No", "No", "No", "Yes",
"Yes", "Yes", "Yes", "No", "No", "No", "Yes", "Yes", "No", "Yes",
"Yes", "No", "Yes", "No", "Yes"), `Rating 1` = c(1L, 1L, 4L,
5L, 3L, 2L, 3L, 1L, 4L, 1L, 4L, 5L, 6L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L), `Member 2` = c("No", "Yes", "No", "Yes", "Yes",
"No", "Yes", "Yes", "Yes", "No", "Yes", "No", "No", "Yes", "No",
"Yes", "No", "Yes", "No", "Yes", "No", "Yes"), `Rating 2` = c(1L,
4L, 1L, 4L, 1L, 4L, 1L, 4L, 1L, 4L, 2L, 2L, 2L, 3L, 4L, 5L, 5L,
1L, 2L, 5L, 3L, 2L)), class = "data.frame", row.names = c(NA,
-22L))
我的目標是通過 R 中的 ggplot 創建一個繪圖,其中 x 軸上有“月份”,y 軸上有“評級”。我的資料包含兩列評級(稱為評級 1 和評級 2)。但是,它們具有相同的比例,因此我可以將 y 軸稱為評級。但是我想在情節中總共有四行。您可以將其視為具有“成員 1”和“評級 1”同時屬于“成員 2”和“評級 2”。所以我想在情節中有四行:
- 成員 1 和是的一行
- 成員 1 和否的一行
- 成員 2 一行,是
- 成員 2 和否的一行
應該有一個包含兩個子組的圖例,每個子組都包含一個標題(標題分別為等級 1 和等級 2):
評分 1:
- 是的
- 不
評分 2:
- 是的
- 不
我是 ggplot 的新手,非常感謝任何幫助。
到目前為止我已經嘗試過:
- 我創建了兩個不同的資料框,一個用于成員 1 及其評級,一個用于成員 2 及其評級。然后我更改了列名,使它們在兩個資料框中都相同。
Data1 <- subset(Data, select=c(Month, `Member 1`, `Rating 1`))
Data2 <- subset(Data, select=c(Month, `Member 1`, `Rating 1`))
colnames(Data1) <- c("Month", "Member", "Rating")
colnames(Data2) <- c("Month", "Member", "Rating")
- 我使用 ggplot 的方式如下:
ggplot()
geom_line(data = Data1, aes(x = Month, y = Rating, group=`Member`, fill=`Member`, color=`Member`, linetype=`Member`), color = "red")
geom_line(data = Data2, aes(x = Month, y = Rating, group=`Member`, fill=`Member`, color=`Member`, linetype=`Member`), color = "blue")
xlab('Month')
ylab('Rating')
當我運行 ggplot 代碼時,我得到一個帶有所需 x 軸和 y 軸的圖。但是,如上所述,我想在右邊有一個圖例。現在,我只有藍色的傳說。此外,如果我可以將其 geom_point用于一個成員,這將是很好的,這使得它更加可視化。
uj5u.com熱心網友回復:
你還沒有說你想要什么型別的情節。在任何情況下,最好將您的資料轉換為長格式以創建繪圖:
library(tidyverse)
df %>%
pivot_longer(-1, names_to = c(".value", "PersonNum"),
names_pattern = "^(.*) (\\d)$") %>%
mutate(Month = as.Date(paste0(Month, "-01"))) %>%
ggplot(aes(Month, Rating, color = Member))
geom_line()
geom_point()
facet_grid(PersonNum~.)
scale_color_manual(values = c('orange2', 'deepskyblue4'))
theme_bw(base_size = 16)

更新
如果您不想要構面,則可以將所有行放在一個面板中。我認為這是一個更難閱讀的情節,并且比帶有方面的情節更有吸引力/資訊量少,但在這里是為了完整性。
df %>%
pivot_longer(-1, names_to = c(".value", "PersonNum"),
names_pattern = "^(.*) (\\d)$") %>%
mutate(Month = as.Date(paste0(Month, "-01")),
Group = paste0('Rating: ', PersonNum, ', Member: ', Member)) %>%
ggplot(aes(Month, Rating, color = Group))
geom_line()
geom_point()
scale_color_brewer(palette = 'Set1')
theme_bw(base_size = 16)

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466732.html
上一篇:如何通過在x軸上使用兩個變數和在y軸上使用分組變數來制作條形圖?
下一篇:指定在x軸上首先標記哪個日期
