Created
August 25, 2016 20:41
-
-
Save const-ae/0d2861f98aec7ab7544de2ae2b3d1e44 to your computer and use it in GitHub Desktop.
My try to recreate the plot from http://www.opiniomics.org/plotting-cool-graphs-in-r/ with ggplot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
df <- data.frame(Circulatory=c(32,26,19,16,14,13,11,11), | |
Mental=c(11,11,18,24,23,24,26,23), | |
Musculoskeletal=c(17,18,13,16,12,18,20,26), | |
Cancer=c(10,15,15,14,16,16,14,14)) | |
rownames(df) <- seq(1975,2010,by=5) | |
df | |
library(ggplot2) | |
library(dplyr) | |
library(reshape2) | |
library(gridExtra) | |
line_data <- df %>% | |
tibble::rownames_to_column("Year") %>% | |
melt(id.vars="Year") %>% | |
mutate(variable = as.character(variable)) %>% | |
as_data_frame() | |
dot_data <- df %>% | |
tibble::rownames_to_column("Year") %>% | |
filter(Year == 1975 | Year == 2010) %>% | |
melt(id.vars="Year") %>% | |
mutate(variable = as.character(variable)) %>% | |
mutate(align=ifelse(Year== 1975, "right", "left")) | |
plots <- lapply(unique(plot_data$variable), function(condition){ | |
dot_data_plus <- mutate(dot_data, visible=ifelse(variable == condition, "a", "b")) | |
p <- line_data %>% | |
mutate(color=ifelse(variable == condition, "a", "b")) %>% | |
ggplot(aes(x=Year, y=value, group=variable)) + | |
geom_line(size=1.2, aes(color=color)) + | |
geom_point(data=dot_data_plus, size=2, aes(alpha=visible)) + | |
geom_text(data=dot_data_plus, aes(label=paste0(" ", value, " "), hjust=align, alpha=visible)) + | |
scale_color_manual(values=c("darkblue", "grey")) + | |
scale_alpha_manual(values=c(1,0),guide="none") + | |
ggtitle(condition) + guides(color=FALSE) | |
if(condition %in% c("Musculoskeletal", "Cancer")){ | |
p + theme_void() + theme(axis.text.x=element_text()) | |
}else{ | |
p + theme_void() | |
} | |
}) | |
grid.arrange(grobs=plots, nrow=2, ncol=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would really like to emphasize certain observations like how you did, however...
I get these two errors:
"Error in unique(plot_data$variable) : object 'plot_data' not found
Error in arrangeGrob(...) : object 'plots' not found"
...any suggestions? thanks!