6

I'm trying to plot a specific graphic on . I would like to plot like this one:

enter image description here

My code is:

library("ggplot2")

exec <- data.frame(
threads = c(2,4,8,16,32,64,2,4,8,16,32,64,2,4,8,16,32,64,2,4,8,16,32,64), 
msgs=c(100,100,100,100,100,100,400,400,400,400,400,400,1600,1600,1600,
       1600,1600,1600,6400,6400,6400,6400,6400,6400),
qtds=c(3778.2,6000,6000,6000,6000,6000,3756.6,7462.8,14666.2,24000,24000,24000,
       3762.4,7445.4,14284.4,27869.8,55877.4,93407.4,2934,5427.4,10717.6,17214.2,
       26222.2,37333.6))

ggplot(data=exec, aes(x=threads, y=qtds, fill=msgs)) + geom_bar(stat="identity", 
       position="dodge")

However, all the msgs are in the same bar, as shown in the image.

enter image description here

How do I fix it?

1
  • 1
    use fill=as.factor(msgs) or covert it to factor before in exec. Since ggplot thinks its a numeric it would "group" on it so you don't get the dodging behavior Commented Jan 19, 2019 at 14:26

1 Answer 1

6

You need to convert the integers to factors. Using as.factor() to converted.

library("ggplot2")

exec <- data.frame(threads = c(2,4,8,16,32,64,2,4,8,16,32,64,2,4,8,16,32,64,2,4,8,16,32,64),  msgs=c("100 msg/min","100 msg/min","100 msg/min","100 msg/min","100 msg/min","100 msg/min","400 msg/min","400 msg/min","400 msg/min","400 msg/min","400 msg/min","400 msg/min","1600 msg/min","1600 msg/min","1600 msg/min","1600 msg/min","1600 msg/min","1600 msg/min","6400 msg/min","6400 msg/min","6400 msg/min","6400 msg/min","6400 msg/min","6400 msg/min"),
        qtds=c(3778.2,6000,6000,6000,6000,6000,3756.6,7462.8,14666.2,24000,24000,24000,3762.4,7445.4,14284.4,27869.8,55877.4,93407.4,2934,5427.4,10717.6,17214.2,26222.2,37333.6))

ggplot(data=exec, aes(x=as.factor(threads), y=qtds, fill=msgs)) +
geom_bar(stat="identity", position="dodge") +
scale_fill_discrete(name = "Msgs") +
  xlab("Threads") +
  ylab("Qtds") +
  theme_bw() +
  theme(legend.position = c(0.22,0.85))

enter image description here

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

2 Comments

It seems nice. But only a question. Is there a way to I change to order? For example: The correct order has to be 100msg/min, then 400 not 1600.
You need to sort in order right. So we can use the "levels." Let's go!! Creating a table with the values of msgs: msg <- table(exec$msgs) getting the names ordered: msg_level <- names(msg)[c(1,3,2,4)] creating a new column in exec df with the values of msgs with the levels ordered: exec$msgs_level <- factor(exec$msgs, levels = msg_level) , and now you use this in ggplot code: fill=msgs_level

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.