Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

How to unstack bar plots in R (plotly)?

I am trying to make a barplot in the Plotly package in R. By default Plotly stacks the values belonging to the same categories. I would like to plot the values sepeartely even if they belong to the same category. Following is an example:

value<-c(1,2,3,4,5)
Feature_Names <- c("A","B","C","D","C")
df1 <- data.frame(Feature_Names, value)
p7<-plot_ly(df1,x=~Feature_Names,y=~value,type='bar') %>%
layout(title= "Feature and values", xaxis= list(title='Feature_Names'))
show(p7)

The output of the above code is : enter image description here

I would like a way to display the values of Feature Name "C" separately as two individual bars. How do I achieve that? Thanks.

question from:https://stackoverflow.com/questions/65878730/how-to-unstack-bar-plots-in-r-plotly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create a group column to distinguish between number of values for each Feature_Names.

df1 <- transform(df1, group = ave(Feature_Names, Feature_Names, FUN = seq_along))

Here are two suggestions that you can use after creating group columns

  1. Using ggplot :
library(ggplot2)
library(plotly)

ggplotly(ggplot(df1, aes(Feature_Names, value, fill = group)) + 
         geom_col(position = 'dodge'))

enter image description here

  1. Using plotly :

For this option you can get the data in wide format and then plot.

df2 <- tidyr::pivot_wider(df1, names_from = group, values_from = value)

plot_ly(df2,x=~Feature_Names,y=~`1`,type='bar', name = 'group 1') %>%
  add_trace(y = ~`2`, name = 'group 2') %>%
  layout(title= "Feature and values", 
         xaxis= list(title='Feature_Names'), yaxis = list(title = 'value'))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...