ARX
ARX

Reputation: 1140

How to plot on R multiple variables on the X axis, and their values on the Y axis?

I have this data frame:

df = data.frame(
  ID = c("foo", "bar", "baz"),
  x  = c(0.30,  0.45,  0.06),
  y  = c(1.33,  0.46,  0.04),
  z  = c(1.47,  0.02,  0.01)
)

I want a point plot with variables x, y and z on the x-axis. On the y-axis, I want the values for each variable, colored by ID. For example, all values for the row with "foo" ID across columns x, y and z could be blue; all values for "bar" could be "red"; and so on. Is this doable with ggplot2, or any other tool?

Upvotes: 1

Views: 4279

Answers (1)

dc37
dc37

Reputation: 16178

With ggplot2, you need to reshape your dataframe into a longer format. You can do it by using the function pivot_longer from tidyr:

library(tidyr)


df %>% pivot_longer(-ID, names_to = "Var", values_to = "val")

# A tibble: 9 x 3
  ID    Var     val
  <fct> <chr> <dbl>
1 foo   x      0.3 
2 foo   y      1.33
3 foo   z      1.47
4 bar   x      0.45
5 bar   y      0.46
6 bar   z      0.02
7 baz   x      0.06
8 baz   y      0.04
9 baz   z      0.01

In these format, your data can be easily use to get a ggplot graph by doing:

library(dplyr)
library(tidyr)
library(ggplot2)

df %>% pivot_longer(-ID, names_to = "Var", values_to = "val") %>%
  ggplot(aes(x = Var, y = val, color = ID))+
  geom_point()

enter image description here

Upvotes: 2

Related Questions