-1

I tried to plot a dataframe in shiny using r. This df has multiple columns (x, y1, y2..). I am not sure how many y are there, but at least one. And I want to plot all figures (y1~x, y2~x....) as a big one. Since I am using shiny, it's also required to plot all of them as one output (a big one).

I tried the first method in this post (facet_grid(series ~ .)). The problem is that different y may be in different magnitude, so I need to plot them separately. But the y-scale is the same for all figures, and I cannot figure out how to scale the y-axis.

Can anyone give me some hint, either functions or settings that I can use to solve this problem? Thanks. (I hope my description is clear enough)

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
Harry
  • 331
  • 1
  • 4
  • 14
  • Provided I have understood you correctly, you need to [reshape data from wide to long](https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format) first; then you can either use facets or map a suitable aesthetic (e.g. `colour`/`shape`) to the different groups. Also: This has nothing to do with `shiny` specifically, so I've removed the tag. Lastly, to give targeted advice/help you are always encouraged to provide reproducible & minimal sample data and code. – Maurits Evers Mar 05 '20 at 22:29

1 Answers1

1

But the y-scale is the same for all figures, and I cannot figure out how to scale the y-axis.

To allow the y-axis to roam free, use the scales="free" option of the facet_grid or facet_wrap functions in ggplot2.

For example,

Stocks %>%
  pivot_longer(cols=-date, values_to="Price") %>%
  ggplot(aes(y=Price, x=date)) +
  geom_line() +
  facet_wrap(~name, scales="free") # <-- 

enter image description here


Data:

Stocks <- data.frame(SE=as.matrix(EuStockMarkets), 
                     date=as.Date(as.numeric(time(EuStockMarkets)) - start(EuStockMarkets)[1], 
                                  origin=as.Date(start(EuStockMarkets)[2], 
                                                 origin = "1991-01-01")))

head(Stocks)
   SE.DAX SE.SMI SE.CAC SE.FTSE       date
1 1628.75 1678.1 1772.8  2443.6 1991-05-11
2 1613.63 1688.5 1750.5  2460.2 1991-05-11
3 1606.51 1678.6 1718.0  2448.2 1991-05-11
4 1621.04 1684.1 1708.1  2470.4 1991-05-11
5 1618.16 1686.6 1723.1  2484.7 1991-05-11
6 1610.61 1671.6 1714.3  2466.8 1991-05-11
Edward
  • 10,360
  • 2
  • 11
  • 26
  • Hi Edward, one more question is that is it possible to adjust the size of each figure (it's OK to use the same size for all figures, just want to enlarge them a little bit). And is it possible to adjust the layout, like in one row, in one column, and 3*5, etc. Thanks for your help. – Harry Mar 06 '20 at 17:33
  • Use `facet_grid(~name)` or `facet_grid(name~.)` with or without `scales="free"`. Or `facet_wrap(~name, nrow=1)`, etc. For manually adjusting the size of each individual facet, I'm not sure that's possible. I'd start a new question for that one. – Edward Mar 06 '20 at 23:42