Python画图笔记
matplotlib的官方网址:http://matplotlib.org/
问题 Python Matplotlib画图,在坐标轴、标题显示这五个字符 ⊥ + - ⊺ ⨁,并且保存后也能显示 http://q.cnblogs.com/q/68725/
matplotlib可以嵌入tex代码,画出的图形添加文字更加的漂亮。
import matplotlib.pyplot as plt import numpy as np x = np.arange(-4, 4, 0.1) f1 = np.power(10, x) f2 = np.power(np.e, x) f3 = np.power(2, x) plt.plot(x, f1, 'r', x, f2, 'b', x, f3, 'g' , linewidth = 2) plt.axis([-4, 4, -0.5, 8]) plt.text(1, 7.5, r'$10^x$', fontsize = 16) plt.text(2.2, 7.5, r'$e^x$', fontsize = 16) plt.text(3.2, 7.5, r'$2^x$', fontsize = 16) plt.title('A simple example', fontsize = 16) plt.savefig('power.png', dpi = 75) plt.show()
可参考
http://matplotlib.org/examples/pylab_examples/mathtext_demo.html
import numpy as np from matplotlib.pyplot import figure, show fig = figure() fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111, axisbg='y') ax.plot([1,2,3], 'r') x = np.arange(0.0, 3.0, 0.1) ax.grid(True) ax.set_xlabel(r'$\Delta_i^j$', fontsize=20) ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20) tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$' ax.text(1, 1.6, tex, fontsize=20, va='bottom') ax.legend([r"$\sqrt{x^2}$"]) ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} \Delta_{i+1}^j$', fontsize=20) show()
比如数据格式是
最后一列表示的是归属的类别, 读入Python的数据returnMat
画出如下效果的图示
代码如下:
import matplotlib.pyplot as plt colors = ['red', 'green', 'blue'] for i in range(3): x = returnMat[returnMat[:, 3] == (i + 1)][:, 1] y = returnMat[returnMat[:, 3] == (i + 1)][:, 2] scale = 30.0*(i + 1) color = colors[i] plt.scatter(x, y, c = color, s = scale, label = color, alpha=0.3, edgecolors='none') plt.legend(("Don't like", "Ordianry", "Very good"), loc = "best") plt.ylabel('Video') plt.xlabel('Fly') plt.title('Test') plt.show()
演示MatPlotLib中如何设置坐标轴主刻度标签和次刻度标签
1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 #--------------------------------------------------- 4 #演示MatPlotLib中设置坐标轴主刻度标签和次刻度标签. 5 6 #对于次刻度显示,如果要使用默认设置只要matplotlib.pyplot.minorticks_on() 7 8 #--------------------------------------------------- 9 10 from pylab import * 11 from matplotlib.ticker import MultipleLocator, FormatStrFormatter 12 13 #--------------------------------------------------- 14 15 xmajorLocator = MultipleLocator(20) #将x主刻度标签设置为20的倍数 16 xmajorFormatter = FormatStrFormatter('%5.1f') #设置x轴标签文本的格式 17 xminorLocator = MultipleLocator(5) #将x轴次刻度标签设置为5的倍数 18 19 20 ymajorLocator = MultipleLocator(0.5) #将y轴主刻度标签设置为0.5的倍数 21 ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签文本的格式 22 yminorLocator = MultipleLocator(0.1) #将此y轴次刻度标签设置为0.1的倍数 23 24 25 26 t = arange(0.0, 100.0, 1) 27 s = sin(0.1*pi*t)*exp(-t*0.01) 28 29 ax = subplot(111) #注意:一般都在ax中设置,不再plot中设置 30 plot(t,s,'--r*') 31 32 33 34 #设置主刻度标签的位置,标签文本的格式 35 ax.xaxis.set_major_locator(xmajorLocator) 36 ax.xaxis.set_major_formatter(xmajorFormatter) 37 38 ax.yaxis.set_major_locator(ymajorLocator) 39 ax.yaxis.set_major_formatter(ymajorFormatter) 40 41 #显示次刻度标签的位置,没有标签文本 42 ax.xaxis.set_minor_locator(xminorLocator) 43 ax.yaxis.set_minor_locator(yminorLocator) 44 45 ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度 46 ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度 47 48 show() 49 50 ##########################################################
matplotlib是支持unicode编码的,出现图1的问题主要是没有找到合适的中文字体,解决方法有两个:
1.直接修改配置文件matplotlibrc
这种方法我没有试过,因为我安装的是python(x,y),配置文件放的地方不一定一致,所以就选择了下面的方法
2.在代码中动态设置(推荐方式)
这种方式不需要修改配置文件,比较方便,推荐该方法,下面是具体步骤:
首先要再python脚本中的开头加上后面的内容:#-*- coding: utf-8 -*-,即用utf8编码
然后在代码中动态设置字体,下面是主要的几行代码
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
plt.xlabel(u"电压差(V)", fontproperties=font)
plt.ylabel(u"介质损耗角差(度)", fontproperties=font)
plt.title(u"介质损耗角和荷电状态SOC关系图",fontproperties=font)
下面举个具体的例子,因为我在网上看了很多例子,都解决不了这个问题,为了方便大家,下面贴出代码,需要的话可以直接贴过去运行:
#-*- coding: utf-8 -*-
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
plt.figure(figsize=(6,6))
x = [1,2,3,4,5,6,7,8]
y = []
for i in x:
y.append(-(i*i)+i+3)
plt.plot(x, y)
plt.title(u'测试程序', fontproperties=font)
plt.xlabel(u'x轴', fontproperties=font)
plt.ylabel(u'y轴', fontproperties=font)
plt.grid(True)
plt.show()
下面是程序的输出
演示如何实现Matplotlib绘图并保存图像但不显示图形的方法
使用Python的Matplotlib的时候,很多任务是批处理的,
中间需要画图,并保存图像,可是不希望每次都把图形显示出来,
可以试一下下面的脚本testplot.py:
import matplotlib
matplotlib.use('Agg')
from matplotlib.pyplot import plot,savefig
x=np.linspace(-4,4,30)
y=np.sin(x);
plot(x,y,'--*b')
savefig('D:/MyFig.jpg')
运行一下,发现没有,图形并没有在屏幕上显示,但是已保存到文件,关键是要设置'Agg'的属性!
Python 画文氏图
https://pypi.python.org/pypi/matplotlib-venn
from matplotlib import pyplot as plt import numpy as np from matplotlib_venn import venn3, venn3_circles plt.figure(figsize=(4,4)) v = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C')) v.get_patch_by_id('100').set_alpha(1.0) v.get_patch_by_id('100').set_color('white') v.get_label_by_id('100').set_text('Unknown') v.get_label_by_id('A').set_text('Set "A"') c = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed') c[0].set_lw(1.0) c[0].set_ls('dotted') plt.title("Sample Venn diagram") plt.annotate('Unknown set', xy=v.get_label_by_id('100').get_position() - np.array([0, 0.05]), xytext=(-70,-70), ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.1), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',color='gray')) plt.show()
用Python画左右双坐标轴
http://matplotlib.org/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.html
""" Demo of how to display two scales on the left and right y axis. This example uses the Fahrenheit and Celsius scales. """ import matplotlib.pyplot as plt import numpy as np def fahrenheit2celsius(temp): """ Returns temperature in Celsius. """ return (5. / 9.) * (temp - 32) def convert_ax_c_to_celsius(ax_f): """ Update second axis according with first axis. """ y1, y2 = ax_f.get_ylim() ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2)) ax_c.figure.canvas.draw() fig, ax_f = plt.subplots() ax_c = ax_f.twinx() # automatically update ylim of ax2 when ylim of ax1 changes. ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius) ax_f.plot(np.linspace(-40, 120, 100)) ax_f.set_xlim(0, 100) ax_f.set_title('Two scales: Fahrenheit and Celsius') ax_f.set_ylabel('Fahrenheit') ax_c.set_ylabel('Celsius') plt.show()
Python 设置标签文字的位置
http://matplotlib.org/examples/pylab_examples/fonts_demo.html
from matplotlib.font_manager import FontProperties import numpy as np import matplotlib.pylab as plt font = FontProperties() font.set_size('large') x = np.linspace(-np.pi, np.pi, 201) plt.plot(x, np.sin(x)) plt.ylabel('sin(x)') plt.title('hello world') plt.text( 2.5, -1.2, '2015-07-07', fontproperties=font) plt.axis('tight')
内容来自 http://reverland.org/python/2012/09/07/matplotlib-tutorial/
from pylab import * X = np.linspace(-np.pi, np.pi, 256,endpoint=True) C,S = np.cos(X), np.sin(X) figure(figsize=(10,6), dpi=80) plot(X, C, color="blue", linewidth=2.5, linestyle="-") plot(X, S, color="red", linewidth=2.5, linestyle="-") #设置边界 xlim(X.min()*1.1, X.max()*1.1) ylim(C.min()*1.1, C.max()*1.1) #设置刻度 xticks( [-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) yticks([-1, 0, +1]) #设置刻度标签 xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$']) #移动轴线 ax = gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) #添加图例 plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") legend(loc='upper left') #注解某些点 t = 2*np.pi/3 plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--") scatter([t,],[np.cos(t),], 50, color ='blue') annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t, np.sin(t)), xycoords='data', xytext=(+10, +30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--") scatter([t,],[np.sin(t),], 50, color ='red') annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) #魔鬼在于细节 for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(16) label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 ))
虫口模型
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from random import random step = 1000 br = 500 parm = np.arange(0.1, 4, 0.01) rs = random() for v in range(step): rs = parm * rs - parm * pow(rs, 2) if v > br: plt.plot(parm, rs, 'o')
(原)python中matplotlib的颜色及线条控制 http://www.cnblogs.com/darkknightzh/p/6117528.html
https://stackoverflow.com/questions/22408237/named-colors-in-matplotlib