0

I am struggling to make bar plot with dual y-axis in R. I found many relevant posts but couldn't find the solution. For example, this is what my data is like:

abc 862054 111552197 xyz 760369 163135388 def 488089 130846735 

I followed this post: Bar Plot with 2 y axes and same x axis in R language and used highcharter package to get this: dual y-axis barplot with highcharter:

enter image description here

However, I need a bar chart with two y-axes on two different sides (one on left and one on right).

Can someone please help me with this? From another answer on this post, Bar Plot with 2 y axes and same x axis in R language, I found the solution when x is list of numbers but in my case x is list of strings, not numbers.

0

1 Answer 1

2

Try this tidyverse approach with ggplot2. The key for double axis plots is to have a scaling factor between the variables to be showed in the plot. Here the code:

library(tidyverse) #Scaling factor sf <- max(df$V2)/max(df$V3) #Transform DF_long <- df %>% mutate(V3 = V3*sf) %>% pivot_longer(names_to = "y_new", values_to = "val", V2:V3) #Plot ggplot(DF_long, aes(x=V1)) + geom_bar( aes(y = val, fill = y_new, group = y_new), stat="identity", position=position_dodge(), color="black", alpha=.6) + scale_fill_manual(values = c("blue", "red")) + scale_y_continuous(name = "V2",labels = scales::comma,sec.axis = sec_axis(~./sf, name="V3", labels = scales::comma))+ labs(fill='variable')+ theme_bw()+ theme(legend.position = 'top', plot.title = element_text(color='black',face='bold',hjust=0.5), axis.text = element_text(color='black',face='bold'), axis.title = element_text(color='black',face='bold'), legend.text = element_text(color='black',face='bold'), legend.title = element_text(color='black',face='bold'))+ ggtitle('My barplot') 

Output:

enter image description here

Some data used:

#Data df <- structure(list(V1 = c("abc", "xyz", "def"), V2 = c(862054L, 760369L, 488089L), V3 = c(111552197L, 163135388L, 130846735L)), class = "data.frame", row.names = c(NA, -3L)) 
Sign up to request clarification or add additional context in comments.

2 Comments

The code by default generates the graph with x-axis labels in alphabetical order. Is there a way to modify code to get x-axis labels in the order we mention in V1?
After pivot_longer() add a new pipe %>% and then mutate(V1=factor(V1,levels=unique(V1),ordered=T)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.