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

7
  • 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 Commented Jan 4, 2018 at 12:36
  • Your question is: "I need to bring all these charts into a single plot" Commented Jan 4, 2018 at 12:39
  • Still, solution would be the same: use reshape2, plot using ggplot2, but apply facet_grid with argument scales = "free" Commented Jan 4, 2018 at 12:42
  • @PoGibas - have updated the question to add clarity, you may consider reverting your duplicate marking. Commented Jan 4, 2018 at 12:53
  • Try using facet_grid(~ variable, scales = "free") for the plot you added. Commented Jan 4, 2018 at 12:54

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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") 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.