13.2 条形图
日常使用最多的图形无外乎散点图、柱形图(分组、堆积、百分比堆积等)
# 简单条形图
library(data.table)
<- as.data.table(diamonds)
diamonds
<- diamonds[, .(cnt = .N), by = .(cut)] %>%
p11 plot_ly(x = ~cut, y = ~cnt, type = "bar") %>%
add_text(
text = ~ scales::comma(cnt), y = ~cnt,
textposition = "top middle",
cliponaxis = FALSE, showlegend = FALSE
)# 分组条形图
<- plot_ly(diamonds,
p12 x = ~cut, color = ~clarity,
colors = "Accent", type = "histogram"
) # 堆积条形图
<- plot_ly(diamonds,
p13 x = ~cut, color = ~clarity,
colors = "Accent", type = "histogram"
%>%
) layout(barmode = "stack")
# 百分比堆积条形图
# p14 <- plot_ly(diamonds,
# x = ~cut, color = ~clarity,
# colors = "Accent", type = "histogram"
# ) %>%
# layout(barmode = "stack", barnorm = "percent") %>%
# config(displayModeBar = F)
# 推荐使用如下方式绘制堆积条形图
= diamonds[, .(cnt = length(carat)), by = .(clarity, cut)] %>%
dat := round(100 * cnt / sum(cnt), 2), by = .(cut)]
.[, pct
<- plot_ly(
p14 data = dat, x = ~cut, y = ~pct, color = ~clarity,
colors = "Set3", type = "bar"
%>%
) layout(barmode = "stack")
::tagList(p11, p12, p13, p14) htmltools