Home > Mobile >  Visualizing over date variable (ggplot)
Visualizing over date variable (ggplot)

Time:03-30

I am trying to visualize sentiment by date, which is formatted as day, month, year.

Here is a sample of variables in my dataset:

str(twitter_posts)

outcome:

tibble [1,068 × 5] (S3: tbl_df/tbl/data.frame)
 $ post                  : chr [1:1068] "السلام عليكم ورحمة الله وبركاتة\r\nياليت المشرفات يثبتوه لنا عشان يكون مرجع للأخبار الجديدة\r\nعن الزيادة مو كل"| __truncated__ "والله انك صادقه والدليل محد رد على موضوعك\r\n\r\nخوافات بجد؟؟\r\n\r\nسمعت عندنا بمدرستنا انهم بيرفعون الراتب عل"| __truncated__ "الله المستعان حتى ماتبغوا نفيد بعضنا\r\nشوفوا التجمعات الثانية كيف\r\nمن جد مالنا كلمة مسموعة" "وتعاونوا على البر والتقوى" ...
 $ date                  : chr [1:1068] "40643" "40643" "40673" "40673" ...
 $ period                : chr [1:1068] "10-Apr-11" "10-Apr-11" "10-May-11" "10-May-11" ...
 $ sentiment             : chr [1:1068] "neutral" "negative" "negative" "positive" ...
 $ treatment_announcement: chr [1:1068] "pre" "pre" "pre" "pre" ...

I am trying to run the following code, and used the code recommended below

twitter_posts %>%
  mutate(date = as.Date(as.numeric(date), origin = "1899-12-30")) %>%
  mutate(date = as.Date(period))%>%
  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()

But I am still receiving an error with the time variables:

"Error: Problem with mutate() column date. ℹ date = as.Date(period). x character string is not in a standard unambiguous format Run rlang::last_error() to see where the error occurred."

CodePudding user response:

Try this:

twitter_posts %>%
  mutate(date = as.Date(as.numeric(date), origin = "1899-12-30")) %>%
  #updated
  mutate(period = parse_date_time(period, "dmy") %>% 
  #mutate(date = as.Date(period))%>%
  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()
  • Related