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

如何在Plots绘图中加粗指定线段且不改变颜色?

解决Plots绘图中最后N段线段加粗且颜色匹配的问题

问题描述:我有一个(579×31)的DataFrame,需要绘制除:date列外的所有列,并且要把最后30个数据点对应的线段加粗。尝试用plot!叠加绘制最后一段数据时,颜色被分配给每个数据点而非整条线段,无法和初始绘图配色保持一致。

问题原因

使用@df宏结合cols(2:end)批量绘制多列时,plot!会将所有列的数据视为一组连续的数据集,此时传入linecolors=colors数组,Plots会把数组中的颜色逐个分配给每个数据点,而非每条线对应一个颜色。

解决方案

不要批量绘制最后一段的所有列,而是逐列循环绘制,为每条线单独指定对应的原始颜色,这样就能保证每条加粗线段的颜色和初始绘图完全一致。

修改后的最小复现代码

using DataFrames
using Plots
using StatsPlots
using Dates

start_date = Date("2021-01-03")
end_date = start_date + Day(4)
df = DataFrame(
  date = start_date:Day(1):end_date,
  col1 = rand(5),
  col2 = rand(5),
  col3 = rand(5),
  col4 = rand(5)
)

# 1. 绘制初始全量数据
p = @df df plot(
  :date, cols(2:5),
  legend=:outerright,
  xlabel="Date",
  ylabel="Close",
  title="Stock Prices",
  size=(1000, 600),
  dpi=300,
  left_margin=5Plots.mm,
  bottom_margin=5Plots.mm,
  legend_title="DJI Stocks",
)

# 2. 获取每条线的原始颜色
colors = [s.plotattributes[:linecolor] for s in p.series_list]

# 3. 逐列绘制最后N段的加粗线段(这里N=3,对应最后3个点的线段)
target_cols = names(df)[2:end]  # 获取除date外的所有列名
last_n_rows = df[end-2:end, :]   # 取最后3行数据

for (idx, col) in enumerate(target_cols)
    @df last_n_rows plot!(
        :date, cols(col),
        linewidth=2,
        linecolor=colors[idx],
        label=nothing  # 不添加新图例
    )
end

display(p)

对应到原始问题的代码

针对你579×31的DataFrame,只需要调整last_n_rows的范围为end-30:end即可:

using DataFrames
using Plots
using StatsPlots

# 假设selection是你的DataFrame子集
p = @df selection plot(
  :date, cols(2:31),
  legend=:outerright,
  xlabel="Date",
  ylabel="Close",
  title="Stock Prices",
  size=(1000, 600),
  dpi=300,
  left_margin=5Plots.mm,
  bottom_margin=5Plots.mm,
  legend_title="DJI Stocks",
)

colors = [s.plotattributes[:linecolor] for s in p.series_list]
target_cols = names(selection)[2:end]
last_n_rows = selection[end-30:end, :]

for (idx, col) in enumerate(target_cols)
    @df last_n_rows plot!(
        :date, cols(col),
        linewidth=2,
        linecolor=colors[idx],
        label=nothing
    )
end

display(p)

这样就能实现:初始绘图的所有线段保持默认样式,最后30个数据点对应的线段加粗,且颜色和原线段完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:42:40