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

MPAndroidChart组合图无法显示折线图问题求助

问题分析与修复方案

1. 移除错误的Renderer替换代码

你在setupChart最后一行将CombinedChart的渲染器替换为BarChartRenderer,这会导致图表仅渲染柱状图,完全忽略折线图的绘制逻辑。直接删除这行代码:

chart?.renderer = BarChartRenderer(chart, chart?.animator, chart?.viewPortHandler)

2. 增强折线图的可见性配置

当前LineDataSet仅设置了颜色,可能因折线过细或无标记点导致看不见,补充以下配置:

val entryData = LineData(LineDataSet(indexPerformanceList, "").apply {
    color = Color.White.hashCode()
    setDrawValues(true)
    // 添加这些属性让折线更明显
    lineWidth = 2f
    setDrawCircles(true)
    circleColor = Color.White.hashCode()
    circleRadius = 3f
})

3. 规范CombinedData的数据添加方式

使用addData替代重复调用setData,更符合CombinedData的设计逻辑,避免潜在的数据覆盖问题:

val combinedData = CombinedData()
combinedData.addData(barEntryData)
combinedData.addData(entryData)

4. 调整绘制层级避免遮挡

将柱状图放在折线图下方绘制,确保折线不会被柱状图遮挡:

chart?.drawOrder = arrayOf(
    DrawOrder.BAR,
    DrawOrder.LINE
)

5. 检查数据映射逻辑

你当前的代码中:

  • 折线数据用的是timePlayed字段
  • 柱状数据用的是indexPerf字段
    如果这和你的业务需求相反,会导致数据对应错误,建议确认字段映射是否正确。

6. 恢复横向滚动功能

在configureXAxis中调用的disableScroll()会禁用横向滚动,若需要滚动效果,删除这行代码:

// 移除此行
disableScroll()

修正后的核心代码示例

fun setupChart(
    values: List<PlayerGraphStatModel>?,
    landScapeMode: Boolean = false
) {
    values ?: return
    
    val indexPerformanceList = dtoToEntry(values.map { it.timePlayed.toFloat() } + values.map { it.timePlayed.toFloat() })
    val timePlayedList = dtoToBarEntry(values.map { it.indexPerf.toFloat() } + values.map { it.indexPerf.toFloat() })
    
    val lineDataSet = LineDataSet(indexPerformanceList, "").apply {
        color = Color.White.hashCode()
        setDrawValues(true)
        lineWidth = 2f
        setDrawCircles(true)
        circleColor = Color.White.hashCode()
        circleRadius = 3f
    }
    val entryData = LineData(lineDataSet)
    
    val barDataSet = BarDataSet(timePlayedList, "").apply {
        color = Color.AiaRed.hashCode()
        setDrawValues(false)
    }
    val barEntryData = BarData(barDataSet)
    
    val combinedData = CombinedData()
    combinedData.addData(barEntryData)
    combinedData.addData(entryData)
    
    chart = this
    formatChart(combinedData, landScapeMode)
    configureXAxis()
    configureYAxis()
}

完成以上修改后,折线图应该能正常显示,同时CombinedChart的横向滚动功能也会正常工作,实现柱状图与折线图叠加的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:35:18