You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言Plotly绘制从大到小的水平累积直方图

Solution for Horizontal Cumulative Histogram in Plotly (R)

Got it, let's tackle this horizontal cumulative histogram request— I've been in a similar spot where I needed to prioritize larger values at the top for readability, so I know exactly what you're going for. Here's a straightforward approach using Plotly's native histogram functionality (no need to manually calculate cumulative counts like you'd have to with bar charts):

Step 1: Prepare Example Data

First, let's simulate data that matches your scenario—values from 1 to 11, with fewer records for larger numbers:

library(plotly)

# Simulate data: more entries for smaller values, fewer for larger
set.seed(123)
data <- data.frame(
  value = c(
    rep(1:5, each=20),
    rep(6:9, each=10),
    rep(10:11, each=3)
  )
)

Step 2: Reorder Categories for the Y-Axis

Since we're making a horizontal plot, our categorical values will live on the Y-axis. We need to convert value to a factor with levels ordered from 11 down to 1 so they display top-to-bottom in descending order:

# Convert to factor with reversed levels (11 to 1)
data$value <- factor(data$value, levels = rev(1:11))

Step 3: Build the Horizontal Cumulative Histogram

Use Plotly's histogram trace, enable cumulative counting, and set orientation='h' for horizontal layout:

plot_ly(data, y = ~value, type = "histogram", orientation = "h") %>%
  layout(
    title = "Horizontal Cumulative Histogram (11 to 1 Top-to-Bottom)",
    yaxis = list(title = "Value"),
    xaxis = list(title = "Cumulative Count"),
    bargap = 0.1 # Optional: adjust gap between bars for readability
  ) %>%
  layout(barmode = "overlay") %>% # Required for cumulative to work correctly
  add_trace(cumulative = list(enabled = TRUE, direction = "increasing"))

Key Details Explained:

  • orientation='h': Switches the histogram to horizontal, placing categories on the Y-axis and counts on the X-axis.
  • Reversed factor levels: Ensures larger values (11, 10...) appear at the top of the Y-axis, which is critical for your readability goal.
  • cumulative = list(enabled = TRUE): Tells Plotly to calculate cumulative counts automatically—no manual aggregation needed (this is why using histogram is better than bar here, since bar charts don't have native cumulative support).
  • barmode = "overlay": A necessary setting to make the cumulative calculation work as expected for categorical histograms.

When you run this code, you'll get a horizontal histogram where each bar shows the cumulative count up to that value, with 11 at the top and 1 at the bottom—perfect for highlighting that smaller values have more records while keeping larger, rarer values visible at the top.

内容的提问来源于stack exchange,提问作者MMAASS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:29:40