0

with a dataframe like below

> set.seed(99)
> data = data.frame(name=c("toyota", "nissan"), a=sample(1:10,2)/10,b=sample(-150:-50,2),c=sample(1e2:1e3,2),d=sample(1e3:1e5,2), e=sample(-15:30,2))
> data
    name   a   b   c     d   e
1 toyota 0.6 -81 582 67471   -7
2 nissan 0.2 -51 969 30163   13

I need to create a bar chart of each of the columns a to e. I could do it individually as ggplot(data, aes(x=name, y=a)) + geom_bar(stat = "identity") which is fine. However I need to bring all these plots into a single chart may be with two columns in an iterative fashion - how to go about this ?

Update 1:-

To add clarity on the question it doesn't make sense to create a single stacked bar chart as the range of the values for each column vary a lot. A simple stacked bar chart as in the answer here would generate a plot like below - which isn't useful for representing some of the variables

enter image description here

Update 2:- with suggestion to use facet_grid(~ variable, scales = "free") doesn't make this any better - see chart below.

enter image description here

user3206440
  • 4,749
  • 15
  • 75
  • 132
  • 1
    @PoGibas the question is different - the ranges of the values for each column vary a lot - so it woudn't make sense to put this in a single chart – user3206440 Jan 04 '18 at 12:36
  • Your question is: "I need to bring all these charts into a single plot" – pogibas Jan 04 '18 at 12:39
  • Still, solution would be the same: use `reshape2`, plot using `ggplot2`, but apply `facet_grid` with argument `scales = "free"` – pogibas Jan 04 '18 at 12:42
  • @PoGibas - have updated the question to add clarity, you may consider reverting your duplicate marking. – user3206440 Jan 04 '18 at 12:53
  • Try using `facet_grid(~ variable, scales = "free")` for the plot you added. – pogibas Jan 04 '18 at 12:54
  • @PoGibas this has the same issue as the plots for columns with larger ranges make the plots with smaller ranges too small to see. – user3206440 Jan 04 '18 at 13:09
  • Please check [`facet tutorial`](http://ggplot2.tidyverse.org/reference/facet_grid.html) – pogibas Jan 04 '18 at 13:10

2 Answers2

1

Perhaps facet_wrap() is better suited for your needs?

library(ggplot2)
library(reshape2)
ggplot(melt(data, id = "name")) + 
  aes(name, value, fill = variable) + 
  geom_col(position = "dodge") +
  facet_wrap(~ variable, scales = "free_y") 

enter image description here

Uwe
  • 41,420
  • 11
  • 90
  • 134
0

Well you need to first melt your data and the plot it, use the created column variable as a grouping colum:

data = data.frame(name=c("toyota", "nissan"), a=sample(1:10,2)/10,b=sample(-150:-50,2),c=sample(1e2:1e3,2),d=sample(1e3:1e5,2), e=sample(-15:30,2))

library(reshape2)
data <- melt(data, id="name")

library(ggplot2)
ggplot(data,aes(x=name, y=value, fill=variable)) + geom_bar(stat = "identity", position = "dodge") 
Mal_a
  • 3,670
  • 1
  • 27
  • 60