Skip to content

Instantly share code, notes, and snippets.

@alexhanna
Created April 22, 2014 13:04
Show Gist options
  • Save alexhanna/11178376 to your computer and use it in GitHub Desktop.
Save alexhanna/11178376 to your computer and use it in GitHub Desktop.
Plot sentiment for candidates
#!/usr/bin/env Rscript
library(ggplot2)
library(grid)
library(lubridate)
library(scales)
# datetimeToEasternDate <- function(x) {
# ## create as UTC
# x <- as.POSIXct(x, format="%Y-%m-%d %H:%M", tz="UTC")
# ## convert to Eastern time
# x <- format(x, tz="America/New_York")
# x <- strptime(x, "%Y-%m-%d")
# x <- as.POSIXct(x)
# }
# df <- rbind(
# read.delim("../data/sentiment-wave2.csv", sep = "\t", header = F),
# read.delim("../data/sentiment-wave3.csv", sep = "\t", header = F)
# )
# names(df) <- c("Date", "Candidate", "Average")
# df$Date <- datetimeToEasternDate(df$Date)
# df <- ddply(df, c("Date", "Candidate"), function(d) mean(d$Average))
# names(df) <- c("Date", "Candidate", "Average")
# p <- ggplot(df)
# p <- p + geom_line( aes(Date, Average, color = factor(Candidate) ) )
# p <- p + scale_color_manual(name = "Candidate",
# values = c("#000099", "#990000"))
# p <- p + ylab("Average sentiment")
# ggsave(p, file = "../pdf/sentimentExample.pdf", width=12, height=8)
boundaries <- c(ymd_hms("2012-10-04 01:00:00"), ymd_hms("2012-10-04 02:30:00"))
df <- read.csv("../data/elex2012-us-debate-sentiment.csv", header = TRUE)
df$date <- ymd_hms(as.character(df$date))
df <- df[which(df$user.level %in% c(1,2)),]
df <- df[which(df$date >= ymd_hms("2012-10-04 00:30:00") & df$date <= ymd_hms("2012-10-04 04:30:00")), ]
p <- ggplot(df, aes(date, mean, color = person))
p <- p + geom_point(aes(shape = factor(user.level)), size = 2, alpha = 0.5) + geom_smooth(aes(linetype = factor(user.level)), method = "loess", alpha = 0)
#p <- p + geom_errorbar( aes(date, mean, ymin = mean - 1.96 * std, ymax = mean + 1.96 * std), alpha = 0.2 )
p <- p + geom_vline( xintercept = as.numeric(boundaries), linetype = 2 )
p <- p + scale_color_manual(name = "Candidates", labels = c("Obama", "Romney"), values = c("blue", "red"))
p <- p + theme_bw() + theme(
legend.text = element_text(size = 24),
legend.title = element_blank(),
# legend.position = c(0.15,0.8),
legend.key.size = unit(1, 'cm'),
axis.text.x = element_text(size = 24, angle = 45, vjust = 0.5),
axis.text.y = element_text(size = 24, hjust = 0),
axis.title.x = element_blank(),
axis.title.y = element_blank())
ggsave(p, file = "../img/elex2012-us-debate-sentiment.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment