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

基于NMonUn字段值调整Matplotlib绘图线条粗细的技术咨询

Adjust Line Thickness Based on NMonUn Values

Got it, here's how you can make lines thicker for higher NMonUn values and thinner for lower ones—we'll normalize the NMonUn range to a reasonable line width scale so the thickness scales proportionally:

Modified Full Code

import pandas as pd
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

dfMonday = pd.read_csv( "0.Mon.csv", encoding = "ISO-8859-1", sep = ';')
dfSlotMean = dfMonday.groupby('slotID', as_index=False).agg(
    NMonUn=('date', 'nunique'), NMonTot = ('date', 'count'), MeanBPM=('tempo', 'mean')
)

dfSlotMean.drop(dfSlotMean[dfSlotMean.NMonUn< 3].index, inplace=True)
df = pd.DataFrame(dfSlotMean)
df.to_csv('1.silMonday.csv', sep = ';', index=False)
print(df)

tick_spacing = 1
fig, ax = plt.subplots(1, 1)

# Set your desired min/max line widths, and get the range of NMonUn values
min_line_width = 1
max_line_width = 5
min_nmon = df['NMonUn'].min()
max_nmon = df['NMonUn'].max()

for _, r in df.iterrows():
    # Normalize NMonUn value to fit within our line width range
    line_width = (r['NMonUn'] - min_nmon) / (max_nmon - min_nmon) * (max_line_width - min_line_width) + min_line_width
    # Plot each line with the calculated thickness
    ax.plot([r['slotID'], r['slotID']+1], [r['MeanBPM']]*2, linewidth=line_width)

ax.xaxis.grid(True)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show() # Added to ensure the plot renders

Quick Breakdown of the Key Changes:

  • Normalization: We take the raw NMonUn values (3 to 11 in your dataset) and map them to a manageable line width range (1 to 5 here). This ensures the thickness difference is visible but not extreme.
  • Customization: Tweak min_line_width and max_line_width if you want thinner/thicker lines overall—for example, setting max_line_width=8 will make the thickest lines more prominent.
  • Plot Display: Added plt.show() to your original code to make sure the plot actually pops up after running.

With this, the line for slotID=7 (with the highest NMonUn=11) will be the thickest, while lines for slotID=15 and 16 (lowest NMonUn=3) will be the thinnest—exactly matching your requirement.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:12:29