我正在嘗試將情緒隨著時間的推移可視化,類似于
多虧了下面的建議,我運行了以下程式并且運行良好:
Visualizing_sentiment %>%
mutate(date = as.Date(date))%>%
count(sentiment, date)%>%
ggplot(aes(x = date, y = n, fill = sentiment))
geom_col()
#geom_col(position = "dodge")
scale_fill_manual(values = c("positive" = "green",
"negative" = "red",
"neutral"= "black"))
scale_x_date(date_labels = "%b-%y")
facet_wrap(~ year(date))
theme_classic()
uj5u.com熱心網友回復:
要隨時間繪制情緒,您需要一個日期列和一個情緒列。然后,您可以使用 count(sentiment, date) 按日期計算情緒,然后您可以沿 x 軸繪制日期,沿 y 軸繪制 n,并按情緒填充。
如果您想要堆疊條形圖,請從 geom_col() 中洗掉 position = "dodge"
library(lubridate)
library(tidyverse)
data <- tibble(
sentiment = c("positive", "positive", "negative", "negative", "neutral", "neutral",
"neutral", "positive", "negative", "neutral", "neutral", "negative",
"negative", "neutral", "neutral", "positive"),
date = c("2010-02-03", "2010-02-03", "2010-02-04", "2010-02-04", "2010-02-04", "2010-02-05",
"2010-02-05", "2010-02-05", "2010-02-05", "2010-02-05", "2010-02-03", "2010-02-04",
"2010-02-04", "2010-02-05", "2010-02-04", "2010-02-04")
)
data %>%
mutate(date = as.Date(date))%>%
count(sentiment, date)%>%
ggplot(aes(x = date, y = n, fill = sentiment))
geom_col(position = "dodge")
scale_fill_manual(values = c("positive" = "green",
"negative" = "red",
"neutral"= "black"))
scale_x_date(date_labels = "%b-%Y")
theme_bw()
我為你添加了一個 scale_x_date() 。%b 代表月份縮寫,%Y 代表年份。如果您只想說“10”而不是“2010”,您可以選擇 %y。
建議如果這樣做多年,將是一個額外的步驟,并使用 facet_wrap() 將每年顯示為單獨的圖表。你可以這樣做:
previous_plotting_code
facet_wrap(~ year(date))
year() 函式將從日期變數中選出年份,由 lubridate 提供。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/364197.html
