Jorge Paredes
Jorge Paredes

Reputation: 1078

How to graph a horizontal number line with values? R

Okay, my data looks like this

Product   Mean    Min    Max
  A       5.15     1      13
  B       6.13     3      8
  C       9.87     1      50

And I need to do a graph like this

Where the left value is Min and Right Value is max, and the green dot is the mean.

Do not take into account the "x" in the line

How can I do this kind of graph?

enter image description here

Upvotes: 1

Views: 710

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76450

Here are two ways, base R and ggplot2.

1. base R.

The points are plotted with plot and the bars with arrows.

y <- as.integer(as.factor(df1$Product))

plot(df1$Mean, y, 
     pch = 16, cex = 3, 
     col = "green", 
     xlim = c(-10, 60),
     ylim = c(0, 4),
     xlab = NA,
     ylab = "Product",
     yaxt = "n")
arrows(x0 = df1$Min, 
       y0 = y, 
       x1 = df1$Max, 
       length = 0.1,
       angle = 90, 
       lwd = 2,
       code = 3)
axis(2, at = y, labels = df1$Product)

enter image description here

2. ggplot2

The code is simpler, use geom_pointrange for the bars and overplot the points after.

library(ggplot2)

ggplot(df1, aes(Mean, Product)) +
  geom_pointrange(aes(xmin = Min, xmax = Max), size = 1.5) +
  geom_point(size = 6, colour = "green") +
  theme_minimal()

enter image description here

If the lines at the end of the bars are needed, use geom_errorbar.

ggplot(df1, aes(Mean, Product)) +
  geom_errorbar(aes(xmin = Min, xmax = Max), 
                size = 1.5, 
                width = 0.25) +
  geom_point(size = 6, colour = "green") +
  theme_minimal()

enter image description here


Data

df1 <- read.table(text = "
Product   Mean    Min    Max
  A       5.15     1      13
  B       6.13     3      8
  C       9.87     1      50
", header = TRUE)

Upvotes: 2

Related Questions