Skip to content

@mollietaylor /customlegend.R
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Using Line Segments to Compare Values in R
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)
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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.