我有以下代码,可以绘制出可变的线宽图:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
x = np.array(range(6))
y = [10, 15,10, 8, 13, 20]
widths = [1, 5,3, 8, 1, 2]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, linewidths=widths,color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,7)
a.set_ylim(0,25)
fig.show()


我想平滑线宽之间的过渡,以使这些变化是渐进的并且看起来不错。我目前正在使用Matplotlib,但不必使用它(如果可行,将使用Seaborn等)。有谁知道如何做到这一点?

最佳答案

另一种选择是使用Polygons代替线段。不幸的是,我不知道如何将线段的width(在points中)转换为Data coordinates。在这里,我手动调整了宽度以尝试匹配所需的结果。

fig, ax = plt.subplots()
ax.set_xlim((0,5))
ax.set_ylim((0,25))

new_w = np.array(widths)/5. # <<< change according to your needs
# FIXME: this should probably be done using some sort of affine
#        transformation already build-in in matplotlib, but I don't know how

for i in range(len(x)-1):
    c = [[x[i], y[i]+new_w[i]/2.],
         [x[i+1], y[i+1]+new_w[i+1]/2.],
         [x[i+1], y[i+1]-new_w[i+1]/2.],
         [x[i], y[i]-new_w[i]/2.]
        ]
    p = matplotlib.patches.Polygon(c)
    ax.add_patch(p)

plt.show()


python - Python:如何绘制线宽可变且逐渐变化的图?-LMLPHP

10-08 02:07