问题描述
matplotlib中有绘制棒状图或者棉棒图stem的功能,官网上给了基础的例程:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2 * np.pi, 41)
y = np.exp(np.sin(x))
plt.stem(x, y, use_line_collection=True)
plt.show()
运行结果如下:
官方并没有明确给出相关的美化函数,想要美化的化,缺少一些资料
解决办法
分析了stem的函数名:
Axes.stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, use_line_collection=False, data=None)
比较重要的在于linefmt、markerfme和basefmt上,这个是设置,可以像plot设置line和marker一样的设置线性和颜色。
bottom这个参数比较特殊,它是说水平基线所处的位置,默认为0,我们可以修改(下面将改为1)。
这个函数的返回描述如下:
containerStemContainer
The container may be treated like a tuple (markerline, stemlines, baseline)
可以看到他返回了有markerline, stemlines, baseline元素的元祖,则我们对其设置就能实现marker、垂线以及基线的个性化设置,使用setp函数,整体代码如下:
import numpy as np
import matplotlib.pyplot as plt
# 生成模拟数据集
x=np.linspace(0,10,20)
y=np.random.randn(20)
# 绘制棉棒图
#这个bottom是决定了棉棒图的基线位置的
markerline, stemlines, baseline = plt.stem(x,y,linefmt='-',markerfmt='o',basefmt='--',label='TestStem',bottom=1)
# 可单独设置棉棒末端,棉棒连线以及基线的属性
plt.setp(stemlines,lw=0.5)
plt.setp(markerline, lw=0.5,
color='k',markersize=0.5) # 将棉棒末端设置为黑色
plt.setp(baseline,lw=0.5)
plt.legend()
plt.show()
运行结果,可见我对其成功进行了丑化,(仅仅是示例而已):
总结
多看matplotlib文档,分析函数返回的变量,虽然有些没有操作没有明确说明,但类型差不多,就能一些常见的参数来美化它们