Python:如何制作具有逐渐变化的可变线条粗细的绘图?

时间:2016-12-23 00:36:01

标签: python matplotlib graph

我有以下代码,它绘制了可变线厚度图:

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等)。有谁知道怎么做?

2 个答案:

答案 0 :(得分:2)

另一种选择是使用Polygons而不是线段。不幸的是,我不知道如何将线段的widthpoints)翻译为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()

enter image description here

答案 1 :(得分:1)

一个不完美的解决方案是以小块的形式剖析每个线段并插入线段的宽度。除了在两个线段之间的角度之外,它的效果非常好,但它是一个开始:

Error parsing query:
Create Edge PurchasedCarts         FROM         (CREATE VERTEX Purchases SET guid = "44b4dab7-744a-4f13-ae55-3a563e327de9", accountId = '240059', amount = 44, orderNumber = "1496890", totalItems = 2)         TO         (Select @rid from Users)
     ^
Encountered " &lt;CREATE&gt; "Create "" at line 1, column 1.
Was expecting one of:
    &lt;SELECT&gt; ...
    &lt;TRAVERSE&gt; ...
    &lt;MATCH&gt; ...
    &lt;INSERT&gt; ...
    &lt;RETURN&gt; ...
    &lt;PROFILE&gt; ...
    &lt;FIND&gt; ...
    &lt;REBUILD&gt; ...
    &lt;OPTIMIZE&gt; ...
    &lt;GRANT&gt; ...
    &lt;REVOKE&gt; ...
    &lt;BEGIN&gt; ...
    &lt;COMMIT&gt; ...
    &lt;ROLLBACK&gt; ...
    &lt;IF&gt; ...
    &lt;SLEEP&gt; ...
    &lt;CONSOLE&gt; ...

    DB name="*****"

enter image description here