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

如何配置折线与点图表数值:按年份区间分组、无数据时折线从0起始

实现方案

针对你提到的两个需求,我们只需要先对y数据集做预处理即可,修改逻辑如下:

  1. 按年份区间分组汇总y的合计值,修正原代码中全局求和的错误
  2. 补全所有存在的年份区间,缺失年份的合计值设为0,让折线从0开始

预处理y的代码如下:

library(dplyr)
library(ggplot2)
library(plotly)
library(data.table)

# 预处理y数据集
y_agg <- y %>%
  # 按年份区间分组求和
  group_by(year_range) %>%
  summarise(total = sum(total), .groups = "drop") %>%
  # 补全x中所有存在的年份区间
  right_join(tibble(year_range = unique(x$year_range)), by = "year_range") %>%
  # 缺失值替换为0
  mutate(total = tidyr::replace_na(total, 0))

修改后的完整可视化代码如下:

Plan <- "#288D55"
x_labels = list(tickangle = -45,tickfont = list(family = "Arial",size = 10,color = "black",face="bold"))
y_labels = list(tickfont = list(family = "Arial",size = 10,color = "black",face="bold"))

ggplotly(
  x %>%
    group_by(year_range) %>%
    mutate(total_year_range = sum(total)) %>%
    ungroup() %>%
    ggplot(aes(x = as.character(year_range), y = total, text = total_year_range))+
    geom_col(aes(fill = Sector))+
    theme_classic()+
    # 使用预处理后的y_agg绘制折线
    geom_line(data = y_agg, aes(x=as.character(year_range), y= total, group=1,color="Plan"),size=0.8)+
    scale_colour_manual(name="",values=Plan)+
    # 使用预处理后的y_agg绘制点
    geom_point(data = y_agg, aes(x=as.character(year_range), y=total),color="#288D55")+
    theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom")+
    labs(x="", y="No.of total companies", fill="")+
    theme(axis.title.y =element_text(size=8))+
    scale_fill_manual(values=c("#1F7A3F","#0AAA4D","#70B821","#9BDFAF"))+
    scale_y_continuous(labels = function(x) format(x, scientific = FALSE),expand = expansion(mult = c(0,.3))),tooltip = c("text"))%>% 
  layout(legend = list(orientation = "h", x = 0.1, y = -0.2,font=list( family='Arial', size=10, color='black')),xaxis = x_labels,yaxis = y_labels)%>%
  config(displaylogo = FALSE,modeBarButtonsToRemove = list('sendDataToCloud', 'autoScale2d', 'resetScale2d', 'toggleSpikelines','hoverClosestCartesian', 'hoverCompareCartesian','zoom2d','pan2d','select2d','lasso2d','zoomIn2d','zoomOut2d'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:09:03