JD kreyfelt
JD kreyfelt

Reputation: 135

Plotting each value of columns for a specific row

I am struggling to plot a specific row from a dataframe. Below is the Graph i am trying to plot. I have tried using ggplot and normal plot but i cannot figure it out.

This is the output I'm am trying to plot

 Wt2 Wt3 Wt4 Wt5 Lngth2 Lngth3 Lngth4 Lngth5
1  48  59  95  82    141    157    168    183
2  59  68 102 102    140    168    174    170
3  61  77  93 107    145    162    172    177
4  54  43 104 104    146    159    176    171
5 100 145 185 247    150    158    168    175
6  68  82  95 118    142    140    178    189
7  68  95 109 111    139    171    176    175

Above is the Data frame I am trying to plot with. The rows are for each bears measurement. So row 1 is for bear 1. How would I plot only the Wt columns for bear 1 against an X-axis that goes from years 2 to 5

Upvotes: 0

Views: 997

Answers (2)

Ricardo Semião
Ricardo Semião

Reputation: 4456

You can pivot your data frame into a longer format:

First add a column with the row number (bear number):

df = cbind("Bear"=as.factor(1:nrow(df)), df)

It needs to be factor so we can pass it as a group variable to ggplot. Now pivot:

df2 = tidyr::pivot_longer(df[,1:5], cols=2:5,
                          names_to="Year", values_to="Weight", names_prefix="Wt")
df2$Year = as.numeric(df2$Year)

We ignore the Length columns with df[,1:5]; say that we only want to pivot the weight columns with df[,2:5]; then say the name of the columns we want to create with names_to and values_to; and lastly the names_prefix="Wt" removes the "Wt" before the column names, leaving only the year number, but we get a character, so we need to make it numeric with as.numeric().

Then plot:

ggplot(df2, aes(x=Year, y=Weight, linetype=Bear)) + geom_line()

Output (Ps: i created my own data, so the actual numbers are off):

enter image description here

Just an addition, if you don't want to specify the columns of your dataset explicity, you can do:

df2 = df2[,grep("Wt|Bear", colnames(df)]
df2 = tidyr::pivot_longer(df2, cols=grep("Wt", colnames(df2)),
                          names_to="Year", values_to="Weight", names_prefix="Wt")

Edit: one plot for each group

You can use facet_wrap:

ggplot(df2, aes(x=Year, y=Weight, linetype=Bear)) +
  facet_wrap(~Bear, nrow=2, ncol=4) +
  geom_line()

Output:

enter image description here

You can change the nrow and ncol as you wish, and can remove the linetype from aes() as you already have a differenciation, but it's not mandatory.

You can also change the levels of the categorical data to make the labels on each graph better, do levels(df2$Bear) = paste("Bear", 1:7) for example (or do that the when creating it).

Upvotes: 2

Yang Wu
Yang Wu

Reputation: 194

Try

ggplot(mapping = aes(x = seq.int(2, 5), y = c(48, 59, 95, 82))) +
  geom_point(color = "blue") +
  geom_line(color = "blue") +
  xlab("Year") +
  ylab("Weight")

Upvotes: 0

Related Questions