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

在R Shiny App中使用Plotly绘制柱状图时格式异常的解决问询

Plotly柱状图格式错乱的原因及修复方案

问题背景

在R Shiny应用中,用ggplot绘制的柱状图显示正常:

# Bar plots
ggplot(data = df_continents) +
  geom_bar(aes(x=country, y=coal_co2), stat="identity", fill="#2596be") +
  scale_y_continuous(labels = number_format())

但改用Plotly实现交互式版本后,图表出现白色横线、格式严重错乱,对应的Plotly代码如下:

# Bar chart - Adding Labels
ticklabels <- seq(from=0, to=round(max(df$coal_co2*100000)), by=100000)
ticktexts <- c(0,paste(ticklabels[-1]/1000, " 000", sep=""))

output$bar <- renderPlotly({
  df %>%
    plot_ly(x =~ country, y = ~ coal_co2, type = "bar", marker = list(color = "#2596be")) %>%
    layout(yaxis=list(tickvals = ticklabels,
                      ticktext = ticktexts
    ))
})

原因分析

  1. 数据集不统一:ggplot使用的是df_continents,而Plotly用的是df,两个数据集的coal_co2数值范围可能差异极大,导致刻度计算完全偏离实际数据。
  2. y轴刻度值与数据范围不匹配:计算ticklabels时把coal_co2放大了100000倍,但Plotly中y轴的原始数据还是coal_co2的原始值,这就导致大量刻度值远超出数据实际范围,那些白色横线就是这些错误的刻度线。
  3. 刻度文本格式化逻辑错误:手动拼接的ticktexts格式和实际数值对应不上,进一步加剧了显示混乱。

修复方案

方案1:统一数据集+使用Plotly自带刻度格式化

确保Plotly和ggplot使用同一个数据集,同时用Plotly内置的tickformat实现和number_format()一致的千位分隔效果,无需手动生成刻度:

output$bar <- renderPlotly({
  df_continents %>%
    plot_ly(x = ~country, y = ~coal_co2, type = "bar", marker = list(color = "#2596be")) %>%
    layout(
      yaxis = list(
        tickformat = ",",  # 自动添加千位分隔符,匹配ggplot的number_format()
        title = "Coal CO2"
      )
    )
})

方案2:手动生成匹配数据的刻度(如需自定义刻度)

如果需要手动设置刻度,必须基于df_continents$coal_co2的实际范围计算,同时用scales包的函数保持和ggplot一致的格式化:

library(scales)

# 基于实际数据范围生成刻度
max_val <- max(df_continents$coal_co2)
tickvals <- seq(from = 0, to = ceiling(max_val), by = ceiling(max_val / 5))  # 按数据分5段
ticktext <- number_format()(tickvals)  # 和ggplot用相同的格式化函数

output$bar <- renderPlotly({
  df_continents %>%
    plot_ly(x = ~country, y = ~coal_co2, type = "bar", marker = list(color = "#2596be")) %>%
    layout(
      yaxis = list(
        tickvals = tickvals,
        ticktext = ticktext
      )
    )
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:56:52