如何控制matplotlib中图形线的宽度?

How to control width of graph line in matplotlib?

我正在尝试用以下数据在matplotlib中绘制折线图,​​属于同一id的x,y点是一条线,所以下面的df中有3条线。

      id     x      y
0      1    0.50    0.0
1      1    1.00    0.3
2      1    1.50    0.5
4      1    2.00    0.7
5      2    0.20    0.0
6      2    1.00    0.8
7      2    1.50    1.0
8      2    2.00    1.2
9      2    3.50    2.0
10     3    0.10    0.0
11     3    1.10    0.5
12     3    3.55    2.2

可以简单的用下面的代码画出来:

import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib notebook

fig, ax = plt.subplots(figsize=(12,8))
cmap = plt.cm.get_cmap("viridis")
groups = df.groupby("id")
ngroups = len(groups)

for i1, (key, grp) in enumerate(groups):
    grp.plot(linestyle="solid", x = "x", y = "y", ax = ax, label = key)

plt.show()

但是,我有另一个数据框 df2,其中给出了每个 id 的权重,我希望找到一种方法来根据它的权重来控制每条线的粗细,权重越大, 较粗的是线。我怎样才能做到这一点?还有什么关系 在线的重量和宽度之间?

  id     weight
0  1          5
1  2         15
2  3          2

如有不明之处请告诉我。

根据评论,您需要了解以下几点:

如何设置线宽?

很简单:linewidth=number。参见 https://matplotlib.org/examples/pylab_examples/set_and_get.html

如何取重并使其显宽?

这取决于你的体重范围。如果它一直在 2 到 15 之间,我建议简单地将它除以 2,即:

linewidth=weight/2

如果您觉得这在美学上令人不快,请除以一个更大的数字,尽管这显然会减少您获得的线宽数量。

如何得到 df2 的权重?

根据您描述的 df2 和您显示的代码,keydf2id。所以你想要:

df2[df2['id'] == key]['weight']

综合起来:

将您的 grp.plot 行替换为以下内容:

grp.plot(linestyle="solid", 
         linewidth=df2[df2['id'] == key]['weight'] / 2.0, 
         x = "x", y = "y", ax = ax, label = key)

(所有这些都是您添加了线宽条目的行。)