julianstanley
julianstanley

Reputation: 1427

ggplot: ranges of values as discrete linerange plots

I would like to make this plot:

Plot 1: The plot that I wanted

My data looks like this:

> head(ranges_example)
  labels Minimum Maximum error
1    One    -275    -240     1
2    Two    -265    -210     1
3  Three    -260    -215     1
4   Four    -273    -230     1
5   Five     NaN    -200     1
6    Six     NaN    -240     1

But, alas, I had to make that plot in illustrator by modifying the plot that I did make in R, this one:

Plot 2: The plot that I got

And I made it using geom_linerange, specifically:

ggplot() +
geom_linerange(data = ranges_example, 
               mapping=aes(x = labels, ymin = Minimum, ymax = Maximum, 
                           lwd = 1, color = error, alpha = 0.5),
               position = position_dodge(width = 1)) +
scale_y_continuous(c(-240, -300)) +
coord_flip() 

Plot 2 is good enough for this once--it takes maybe 15 minutes to turn it into Plot 1 in Illustrator--but I'll probably need to make a good few more of these.

The reason why I don't just remove the position_dodge statement is that then it just blends the colors together, like this:

I need them to be their own, distinct colors so that it's easy to tell them apart. The different shades mean different things and I need to be able to easily distinguish between and alter them.

How can I create a plot that looks more like Plot 2 right out of the box?

Upvotes: 1

Views: 821

Answers (1)

Jon Spring
Jon Spring

Reputation: 66705

ggplot() +
  geom_linerange(data = ranges_example %>% arrange(-error), 
                 mapping=aes(x = labels, ymin = Minimum, ymax = Maximum, 
                             lwd = 1, color = error)) +
  scale_y_continuous(c(-240, -300)) +
  scale_color_continuous(high = "lightgreen", low = "forestgreen") +
  coord_flip()  +
  theme_classic()

enter image description here

# Example data
ranges_example <- tribble(
  ~labels, ~Minimum, ~Maximum, ~error,
    "One",    -275,    -240,     1,
    "Two",    -265,    -210,     1,
    "One",    -285,    -215,     2,
    "Two",    -275,    -190,     2,
    "One",    -300,    -200,     3,
    "Two",    -290,    -180,     3)

Upvotes: 2

Related Questions