多组分组图表(在同一地块上)不使用“变换”在r情节中
代码:
library(plotly)
library(tidyverse)
df <- data.frame(protein = c("Chicken", "Beef", "Pork", "Fish",
"Chicken", "Beef", "Pork", "Fish"),
y1 = c(3, 24, 36, 49, 7, 15, 34, 49),
y2 = c(9, 28, 40, 47, 8, 20, 30, 40 ),
gender = c("Male", "Male", "Male", "Male",
"Female", "Female", "Female", "Female"))
df %>%
plot_ly() %>%
add_bars (y = ~y1, x = ~protein,
name = 'y1.male') %>% add_bars(y = ~y2,
x=~protein, color = I("green"),name = "y2.male")%>%
add_bars(y = ~y1, x = ~protein, color = I("black"),
name = 'y1.female') %>% add_bars(y = ~y2,
x=~protein, color = I("red"), name = "y2.female")
我所需的结果是创建与此类似的东西:
img src =“ https://i.sstatic.net/yi4xh.png”
< 您运行代码,您会发现它已在每个栏中堆叠了“男性”和“女性”值。我希望“ y1.male”在y = y1,“ y2.male”时表示“男性”数据,以表示y = y2,y1.female”时表示“男性”数据,以表示“女性”数据y = y1和“ y2.female”分别表示y = y2时表示“女性”数据。我该如何执行此操作,而不必在r-plotly中使用“变换”过滤器?
Code:
library(plotly)
library(tidyverse)
df <- data.frame(protein = c("Chicken", "Beef", "Pork", "Fish",
"Chicken", "Beef", "Pork", "Fish"),
y1 = c(3, 24, 36, 49, 7, 15, 34, 49),
y2 = c(9, 28, 40, 47, 8, 20, 30, 40 ),
gender = c("Male", "Male", "Male", "Male",
"Female", "Female", "Female", "Female"))
df %>%
plot_ly() %>%
add_bars (y = ~y1, x = ~protein,
name = 'y1.male') %>% add_bars(y = ~y2,
x=~protein, color = I("green"),name = "y2.male")%>%
add_bars(y = ~y1, x = ~protein, color = I("black"),
name = 'y1.female') %>% add_bars(y = ~y2,
x=~protein, color = I("red"), name = "y2.female")
My desired result is to create something similar to this:
However when you run the code, you'll see that it has stacked the "Male" and "Female" values in each bar. I would like "y1.male" to represent the "Male" data when y = y1, "y2.male" to represent the "Male" data when y = y2, "y1.female" to represent the "Female" data when y = y1, and "y2.female" to represent the "Female" data when y = y2, respectively. How can I go about doing this without having to use filter by "transforms" in r-plotly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以将数据重新排列为长格式,然后绘制它:
We can rearrange the data to be in long format and then plot it: