在 r plotly 中不使用 "transforms" 的多组分组条形图(在同一图上)
Multiple sets of grouped bar charts (on the same plot) without using "transforms" in r plotly
代码:
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")
我想要的结果是创建类似这样的东西:
但是当您 运行 代码时,您会看到它在每个栏中堆叠了“男性”和“女性”值。我想用“y1.male”代表y=y1时的“男”数据,“y2.male”代表y=y2时的“男”数据,“y1.female”代表y = y1 时的“女性”数据,以及 y = y2 时的“y2.female”代表“女性”数据。我怎样才能做到这一点而不必在 r-plotly 中通过“转换”使用过滤器?
我们可以将数据重新排列为长格式,然后绘制它:
df %>%
pivot_longer(cols = c(y1, y2)) %>%
unite(gender_var, c(gender, name)) %>%
plot_ly() %>%
add_bars (x = ~protein, y = ~value,
name = ~gender_var)
代码:
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")
我想要的结果是创建类似这样的东西:
但是当您 运行 代码时,您会看到它在每个栏中堆叠了“男性”和“女性”值。我想用“y1.male”代表y=y1时的“男”数据,“y2.male”代表y=y2时的“男”数据,“y1.female”代表y = y1 时的“女性”数据,以及 y = y2 时的“y2.female”代表“女性”数据。我怎样才能做到这一点而不必在 r-plotly 中通过“转换”使用过滤器?
我们可以将数据重新排列为长格式,然后绘制它:
df %>%
pivot_longer(cols = c(y1, y2)) %>%
unite(gender_var, c(gender, name)) %>%
plot_ly() %>%
add_bars (x = ~protein, y = ~value,
name = ~gender_var)