matplotlib 随记

1、安装

window平台下推荐安装Enthought canopy,包含matplotlib和它所依赖的包;
linux下一般默认内置了matplotlib,直接使用就可以了。
 

2、在没有图形界面的Linux系统中,引用pyplot等会调用display的模块时,在之前加这么两句(切记):
import matplotlib
matplotlib.use('Agg')
 

3、示例:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.ticker import MultipleLocator
from matplotlib.dates import DateFormatter
 
fig = plt.figure(111, figsize=(13,6))  # figure 定义一张图片, figsize决定图片的大小  
ax = fig.add_subplot()  # 在图片上定义一块绘图区域,可以通过 fig.gca() 获得
ax = fig.add_axes([0.08, 0.15, 0.82, 0.8])  #  [left, bottom, width, height]
x = arange(0, 30, 1)
x1 = .....
ax.plot(x, y1, label=u'群聊', color='red', linewidth=2)  # 绘制线,并设置属性 
y1 = .....
ax.plot(x, y1, label=u'私聊', color='blue', linewidth=2)  # 绘制另一条线
ax.legend(loc='center left', bbox_to_anchor=(1,0.5))  # 设置图例的位置
xaxis = ax.xaxis  # 获取绘图区域的x轴
yaxis = ax.yaxis  # 获取绘图区域的y轴
xaxis.set_major_locator(MultipleLocator(1))  # x轴的坐标间隔设置为1
xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))  # 格式化日期
fig.autofmt_xdate()  # 自动格式化日期,防止其溢出绘图区域
for label in xaxis.get_ticklabels():  # 设置x轴上显示文本的样式
    label.set_rotation(60)
    label.set_fontsize(13)
fig.subplots_adjust(hspace=0.3# 透明度
plt.grid()  # 显示网格
~~~~~~~~~到这里就可以显示了,plt.show()就可以了,下面是在Django中的用法~~~~~~
canvas = FigureCanvas(fig)
response = django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
~~~~~~~~~把matplotlib生成的图像插入到excel中(先保存到本地,然后转为bmp格式,最后插入到excel中)~~~~~
    file_in = 'temp.png'
    file_out = 'temp.bmp'
    fig.savefig(file_in)  
    img = Image.open(file_in)
    img.load() # 这句不可少,否则会出错
    if len(img.split()) == 4:
        r, g, b, a = img.split()
        img = Image.merge('RGB', (r, g, b))
    img.save(file_out)

    # 插入bmp图像
    ws.insert_bitmap(file_out, 0, 4)

    # 用完之后记得删除
    if os.path.exists(file_in) and os.path.exists(file_out):
        os.remove(file_in)
        os.remove(file_out)

4、matplotlib输出图象的中文显示问题

(1)找到c:\python24\lib\site-packages\matplotlib\mpl-data\matplotlibrc  (修改font.sans-serif、verbose.level两行代码)

(2)找到了matplotlibrc设置文件,是个文本文件,随便找个编辑器打开它,找到font.sans-serif一行,将后边直接改成一个nothing;(把 “:”后的“#......”都去掉)

(3)找到verbose.level一行,把默认的silent改成debug.

(4)找到Vera.ttf,将Vera.ttf用一个中文TrueType文字替换,名字是Vera,后缀是.ttf(True Type Font),即可。

(5)字符串,都用u"..."的形式.(文件编码utf-8 加上" # coding = utf-8  "一行.)

 
4、参考文章:
How to put the legend out of the plot (如何设置图例)
 





posted on 2014-04-14 22:46  fish_1949  阅读(2035)  评论(0编辑  收藏  举报

导航