Reputation: 13363
I have a dataset with a discrete, ordered factor on the x-axis. I'd like to change the rendering from a bar graph to a line graph (in the style of geom_freqpoly
). I can't use geom_freqpoly
straight because I already have my data aggregated, and I don't know how to change the statistic from stat = "bin"
to stat = "identity"
. How can I make this happen?
Here's the data:
temp <- structure(list(wday = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L,
4L, 5L, 5L, 6L, 6L, 7L, 7L), .Label = c("Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), class = c("ordered",
"factor")), splitter = c(FALSE, TRUE, FALSE, TRUE, FALSE, TRUE,
FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE), N = c(250245,
40845, 209685, 45946, 200983, 49403, 142869, 52212, 88589, 48175,
51061, 25317, 84012, 7994), price1 = c(22.79, 70.20, 35.92, 87.66,
48.98, 55.37, 22.56, 88.50, 26.12, 63.29, 35.88, 73.79, 33.12, 82.80
)), .Names = c("wday", "splitter", "N", "price1"), class = "data.frame",
row.names = c(NA, -14L))
And here's the plot:
ggplot(melt(temp,id.vars = c("wday","splitter")),
aes(x = wday, y = value, fill = splitter)) +
geom_bar(stat = "identity", position = "dodge") +
facet_grid(variable ~ ., scale = "free_y")
Though I would think the following code would work, it does not:
ggplot(melt(temp,id.vars = c("wday","splitter")),
aes(x = wday, y = value, colour = splitter)) +
geom_point() + geom_line() +
facet_grid(variable ~ ., scale = "free_y")
Upvotes: 3
Views: 2040
Reputation: 13363
The issue was a missing group aesthetic. The function geom_line
uses the factors as the default grouping variables (here, wday
and splitter
), and so each group is a single data point. Specifying the grouping in aes
renders the lines as desired:
ggplot(melt(temp,id.vars = c("wday","splitter")),
aes(x = wday, y = value, colour = splitter, group = splitter)) +
geom_point() + geom_line() +
facet_grid(variable ~ ., scale = "free_y")
Upvotes: 3