给出以下数据框:
structure(list(Event = c(NA, "Safari Zone Europe", "Community Day",
"Shiny Lugia Raid", "Community Day", NA, "Community Day", NA,
"Community Day", NA, NA, "Dortmund Safari Zone", "Dortmund Safari Zone",
"Community Day", "Chicago Go Fest", "Chicago Go Fest", "Chicago Go Fest",
"Zapdos Raid Day", NA, NA), Pokémon = c("Magikarp", "Magikarp, Pikachu",
"Dratini, Swablu", "Lugia", "Mareep", "Magikarp", "Charmander",
"Pichu", "Larvitar", "Wailmer", "Mawile", "Roselia", "Roselia",
"Squirtle, Squirtle (sunglasses)", "Minun, Shuppet", "Plusle",
"Minun", "Zapdos", "Mawile", "Swablu"), Date = structure(c(1502323200,
1507334400, 1519430400, 1522368000, 1523750400, 1526515200, 1526688000,
1527638400, 1529107200, 1529452800, 1529971200, 1530403200, 1530662400,
1531008000, 1531526400, 1531612800, 1531699200, 1532131200, 1532649600,
1533513600), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
Catches = c(1, 7, 9, 1, 15, 1, 4, 1, 8, 1, 1, 2, 1, 4, 3,
2, 1, 1, 1, 1), `Accumulated catches` = c(1, 8, 17, 18, 33,
34, 38, 39, 47, 48, 49, 51, 52, 56, 59, 61, 62, 63, 64, 65
)), .Names = c("Event", "Pokémon", "Date", "Catches", "Accumulated catches"
), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"
))
当我尝试用x轴上的“日期”和y轴上的“累计捕获量”绘制数据时,我使用以下ggplot代码:
ggplot(Shiny_List, aes(x=`Date`, y=`Accumulated catches`)) +
ggtitle("Shiny catches (dates based on GMT+1)") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_point() +
geom_line() +
geom_text(aes(label=Pokémon),hjust=0, vjust=1.0)
这给了我每个数据点之间的界线。
但是,接下来,我想基于数据帧中的“事件”列来区分某些数据点,因此我将color=Event
添加到了aes()
部分我的ggplot是这样的:
ggplot(Shiny_List, aes(x=`Date`, y=`Accumulated catches`, color=Event)) +
ggtitle("Shiny catches (dates based on GMT+1)") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_point() +
geom_line() +
geom_text(aes(label=Pokémon),hjust=0, vjust=1.0)
由此产生的结果破坏了数据点之间的线。现在,它为“事件”列中的每个唯一值创建了单独的线,而不是像上图中那样仅在所有数据点之间仅创建了一条线。
有什么方法可以保留不同数据点的颜色,并使R忽略geom_line()
部分的颜色,以便为所有数据点创建一行,就像在开始吗?
为了记录,我也尝试了geom_path()
,但是它什么也没有改变。
答案 0 :(得分:2)
通常,最好将属性映射到几何,而不是顶层ggplot
对象。这样可以进行更好的控制。
在这种情况下,将颜色映射到这些点。
ggplot(Shiny_List, aes(x = `Date`,
y = `Accumulated catches`)) +
ggtitle("Shiny catches (dates based on GMT+1)") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_point(aes(color=Event)) +
geom_line() +
geom_text(aes(label = Pokémon),
hjust = 0,
vjust = 1.0)