public
Last active

Using Line Segments to Compare Values in R

  • Download Gist
customlegend.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
library(RColorBrewer)
colors = brewer.pal(8, "Dark2")
 
library(ggplot2)
 
data <- as.data.frame(USPersonalExpenditure) # data from package datasets
data$Category <- as.character(rownames(USPersonalExpenditure)) # this makes things simpler later
 
ggplot(data,
aes(x = Expenditure,
y = Category)) +
labs(x = "Expenditure",
y = "Category") +
geom_segment(aes(x = data$"1940",
y = Category,
xend = data$"1960",
yend = Category),
size = 1) +
geom_point(aes(x = data$"1940",
color = "1940"), # these can be any string, they just need to be unique identifiers
size = 4,
shape = 15) +
geom_point(aes(x = data$"1960",
color = "1960"),
size = 4,
shape = 15) +
theme(legend.position = "bottom") +
scale_color_manual(name = "Year", # or name = element_blank()
labels = c(1940, 1960),
values = colors)
segments.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
library(ggplot2)
 
data <- as.data.frame(USPersonalExpenditure) # data from package datasets
data$Category <- as.character(rownames(USPersonalExpenditure)) # this makes things simpler later
 
ggplot(data,
aes(x = Expenditure,
y = Category)) +
labs(x = "Expenditure",
y = "Category") +
geom_segment(aes(x = data$"1940",
y = Category,
xend = data$"1960",
yend = Category),
size = 1) +
geom_point(aes(x = data$"1940",
color = "1940"),
size = 4, shape = 15) +
geom_point(aes(x = data$"1960",
color = "1960"),
size = 4, shape = 15) +
scale_color_discrete(name = "Year") +
theme(legend.position = "bottom")

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.