mario mario - 1 month ago 7
R Question

Change color and add shape to lines on ggplo2 freq_plot

I'm trying to add shapes on the lines plotted using geom_freqpoly to give more visibility to them if the plot is printed b/w on paper.

data <- data.frame(time=runif(1000,0,20000),
class=c("a","b","c","d"))

ggplot(data, aes(time, colour = class)) + geom_freqpoly(binwidth = 1000) + geom_point(aes(shape=class))


but this generates this error:
'Error: geom_point requires the following missing aesthetics: y'

How can I solve this error?

Another thing is that I want to use a single colour (eg. blue) to draw the lines
but with
scale_colour_brewer()
I can't change the colour scale, I want to change it because the lightest colour is nearly white and you can barely see it.

How can I add a custom min and max for the colours?

enter image description here

Answer

How about this? The error you are getting is being produced by geom_point which needs x and y, so I removed it.

ggplot(data, aes(x = time, color = class)) + 
  geom_freqpoly(binwidth = 1000) +
  scale_color_brewer(palette = "Blues") +
  theme_dark()

enter image description here

If you don't want the dark background, pass manual values from RColorBrewer. The following example uses every second color to increase the contrast.

p1 <- ggplot(data, aes(x = time, color = class)) + 
  geom_freqpoly(binwidth = 1000) +
  scale_color_manual(values = RColorBrewer::brewer.pal(9, name = "Blues")[c(3, 5, 7, 9)])

EDIT

You can extract summarised data from a ggplot object using layer_data function.

xy <- layer_data(p1)

ggplot(xy, aes(x = x, y = count, color = colour)) +
  theme_bw() +
  geom_line() +
  geom_point() +
  scale_color_manual(values = RColorBrewer::brewer.pal(9, name = "Blues")[c(3, 5, 7, 9)])
Comments