【发布时间】:2018-08-08 07:40:38
【问题描述】:
给定以下数据框:
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 添加到我的 ggplot 的 aes() 部分中:
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(),但没有任何改变。
【问题讨论】:
-
我认为您只需要将颜色映射添加到
geom_point而不是ggplot。即:+ geom_point(aes(color = Event)). -
@neilfws 这确实成功了!谢谢!
-
好。我会添加它作为答案。
标签: r