matplotlib绘图进阶

http://blog.csdn.net/pipisorry/article/details/37766161

远程绘图,在matplotlib中的一个坐标轴上画一条直线光标,绘制LaTeX数学公式,对数坐标轴。

远程绘图

Python使用ssh进行远程解释器绘图时出错:RuntimeError: Invalid DISPLAY variable

主要原因:

By default, matplotlib will use something like the TkAgg backend. This requires an X-server to be running.

解决1:

import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
但是这个并不能使代码在远程执行,而在本地绘图,只能将绘图保存为图片文件再下载下来看。

[How to save a figure remotely with pylab? [duplicate]]

解决2:

[How do you plot a graph when developing on a remote machine through ssh only]

[Matplotlib: display plot on a remote machine]

解决3:代码在远程执行,而在本地绘图

The upcoming release (1.4.0, should be out by end of August 2014, release candidates are available) will ship with the nbagg backend which provides interactive figures with out needing to Go to native clients or resorting to using d3. All you need to do in your note book is:

import matplotlib
matplotlib.use('nbagg')
from matplotlib import pyplot as plt

And then to plot

plt.plot(range(3))
plt.show()

[how to display matplotlib plots on local machine?]

1) on remote host (VPS, Ubuntu 16.04) I had to install X11 server, which I did by:

sudo apt-get install xorg
sudo apt-get install openbox

2) On remote host I had to make sure that X11Forwarding is enabled in /etc/ssh/sshd_config

3) On local Win10 machine I had to install Xming server and launch it with default settings.

4) On local Win10 machine I had to configure Putty to use X11 forwarding (Connection-> SSH -> X11 Forwarding) with default settings and keep connection open while running PyCharm (it seems there is no option in PyCharm to enable x11 forwarding, so putty must be running in the background)

5) On remote machine I had to check Display number (echo $DISPLAY) - this can be different for everyone. For me it was localhost:10.0

6) In PyCharm Run configuration -> Environment variables I had to add DISPLAY=localhost:10.0

After all these steps and Putty+Xming running in backgroud, I was able to execute remote code and bring graphic back to my Windows 10 PC!

[ Python plotting on remote server using PyCharm]

皮皮blog





在matplotlib中的一个坐标轴上画一条直线光标

matplotlib.widgets.Cursor

# set useblit = True on gtkagg for enhanced performance

# horizOn=True时,两个坐标都有显示光标

[matplotlib.widgets.Cursor]

示例

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor

t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2 * np.pi * t)
plt.plot(t, s1)

cursor = Cursor(plt.gca(), horizOn=True, color='r', lw=1)
plt.show()

Note: 一个神奇的事情就是,Cursor()必须有一个赋值给cursor,否则并不会显示光标(ubuntu16.04下)。之前在windows下绘制时不用赋值也是会有光标显示的。

结果示图(随着光标的移动,在图中x坐标上会画一条竖线,并在下方显示坐标):

同时在两个子图的两个坐标轴之间画一条直线光标

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor

t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(t, s1)


ax2 = fig.add_subplot(212, sharex=ax1)
ax2.plot(t, s2)

multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1)
plt.show()

[widgets example code: multicursor.py]

皮皮blog




绘制LaTeX数学公式

1. matplotlib.rcParams属性字典,想要它正常工作,在matplotlibrc配置文件中需要设置text.markup = "tex"。

2. 如果你希望图表中所有的文字(包括坐标轴刻度标记)都是LaTeX'd,需要在matplotlibrc中设置text.usetex = True。如果你使用LaTeX撰写论文,那么这一点对于使图表和论文中其余部分保持一致是很有用的。

Matlplotlib对LaTeX有一定的支持,如果记得使用raw字符串语法会很自然:xlabel(r" x2y4 ")

书写数学公式

You can use a subset TeX markup in any matplotlib text string byplacing it inside a pair of dollar signs ($).mathtext开始和结束的字符都要是 $ 。

Note that you do not need to have TeX installed, since matplotlibships its own TeX expression parser, layout engine and fonts.

在matplotlib里面,可以使用LaTex的命令来编辑公式,只需要在字符串前面加一个“r”即可。(在python raw string需要r‘’,表示不转义)Any text element can use math text. You should use raw strings(precede the quotes with an 'r'), and surround the math text withdollar signs ($)

Here is a simple example:  plt.title('alpha > beta')

produces “alpha > beta”.

Whereas this:     

plt.title(r'$\alpha > \beta$')

produces "".

Subscripts and superscripts

To make subscripts and superscripts, use the '_' and '^' symbols:

r'$\alpha_i > \beta_i$'
双下标表示 E_{ij}

符号表示及参考[Writing mathematical expressions]

示例

1

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
         fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()
../_images/pyplot_mathtext.png

2

In [6]: ax.text(2, 8, r"$ \mu \alpha \tau \pi \lambda \omega \tau \lambda \iota \beta $");

In [7]: ax.text(2, 6, r"$ \lim_{x \rightarrow 0} \frac{1}{x} $");
In [8]: ax.text(2, 4, r"$ a \ \leq \ b \ \leq \ c \ \Rightarrow \ a \ \leq \ c$");
In [9]: ax.text(2, 2, r"$ \sum_{i=1}^{\infty}\ x_i^2$");
In [10]: ax.text(4, 8, r"$ \sin(0) = \cos(\frac{\pi}{2})$");
In [11]: ax.text(4, 6, r"$ \sqrt[3]{x} = \sqrt{y}$");
In [12]: ax.text(4, 4, r"$ \neg (a \wedge b) \Leftrightarrow \neg a \vee \neg b$");
In [13]: ax.text(4, 2, r"$ \int_a^b f(x)dx$");

image

[Text rendering With LaTeX]

[Matplotlib for Python Developers]

[LaTeX科技排版]

皮皮blog


对数坐标轴

在实际中,我们可能经常会用到对数坐标轴,这时可以用下面的三个函数来实现

ax.semilogx(x,y) #x轴为对数坐标轴

ax.semilogy(x,y) #y轴为对数坐标轴

ax.loglog(x,y) #双对数坐标轴

from:http://blog.csdn.net/pipisorry/article/details/37766161

ref:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是Matplotlib进阶代码示例: 1. 设置字体大小和样式 ```python import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 14, 'font.family': 'Times New Roman'}) ``` 2. 添加图例 ```python import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 100) y1 = np.sin(x) y2 = np.cos(x) plt.plot(x, y1, label='Sin') plt.plot(x, y2, label='Cos') plt.legend(loc='upper right') plt.show() ``` 3. 设置坐标轴范围和标签 ```python import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.xlim([0, 2*np.pi]) plt.ylim([-1, 1]) plt.xlabel('X Axis') plt.ylabel('Y Axis') plt.show() ``` 4. 添加文本注释 ```python import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.annotate('Maximum', xy=(np.pi/2, 1), xytext=(np.pi/2, 1.5), arrowprops=dict(facecolor='black', shrink=0.05)) plt.show() ``` 5. 使用子图 ```python import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 100) y1 = np.sin(x) y2 = np.cos(x) fig, axs = plt.subplots(2, 1) axs[0].plot(x, y1) axs[0].set_title('Sin') axs[1].plot(x, y2) axs[1].set_title('Cos') plt.show() ``` 这些示例代码可以帮助您更好地理解Matplotlib的高级功能。 ### 回答2: Matplotlib是一种Python的数据可视化库,可以帮助我们创建各种类型的图表和图形。下面是一些Matplotlib进阶代码的示例: 1. 子图划分: 使用`plt.subplot()`函数可以将整个绘图区域划分为多个子图,可以是网格状或自定义形状。可以通过指定行数、列数和子图位置来确定子图的位置。 2. 图表样式设置: 使用`plt.style`来设置图表的样式,如带有背景网格的`'ggplot'`风格或简洁的`'seaborn'`风格等。 3. 自定义图表颜色: 可以使用RGB、HEX或颜色名称等方式来自定义图表中的颜色。例如,通过`color`参数指定颜色,或者通过`plt.cm.colors`模块使用更高级的颜色映射。 4. 图表标签和注释: 使用`plt.xlabel()`和`plt.ylabel()`函数可以设置横轴和纵轴标签,使用`plt.title()`函数可以设置图表标题。可以使用`plt.annotate()`函数在图表上添加注释。 5. 图例设置: 使用`plt.legend()`来添加图例并设置其位置。可以选择在图表内部或外部显示图例,也可以使用`bbox_to_anchor`参数进行更精细的位置控制。 6. 坐标轴设置: 可以使用`ax.tick_params()`函数来设置坐标轴的刻度、标签和网格线的样式。可以通过设置`xlabelpad`和`ylabelpad`参数来调整坐标轴标签与坐标轴之间的间距。 7. 3D图形绘制: Matplotlib还提供了在三维空间中绘制点、线和曲面的功能。可以使用`mpl_toolkits.mplot3d`模块中的`Axes3D`对象来创建三维坐标系。 8. 动画效果: 通过使用`animation`模块,可以在Matplotlib中创建动画效果。可以使用`FuncAnimation`函数来生成一个动画对象,并通过`save()`函数将动画保存为视频或动态GIF。 这只是一些Matplotlib进阶代码示例,实际应用中还有更多的功能和技巧。通过不断学习和实践,可以在数据可视化中充分发挥Matplotlib的优势。 ### 回答3: Matplotlib是一个用于绘制数据可视化图形的Python库。它提供了广泛的绘图选项和灵活的配置参数,使得用户可以轻松地创建各种类型的图形。 Matplotlib进阶代码包括许多功能和技巧,可以让图形更加美观和具有专业水准。以下是一些可以用于进阶Matplotlib代码的示例: 1. 改变图形风格:Matplotlib提供了不同的图形风格供选择,可以通过设置`plt.style.use()`来更改图形的样式,例如:"ggplot"、"seaborn"、"fivethirtyeight"等。 2. 自定义颜色和线型:可以通过设置`plt.plot()`函数的`color`和`linestyle`参数来自定义图形的颜色和线型。 3. 添加图例和标签:可以通过`plt.legend()`函数来添加图例,通过`plt.xlabel()`和`plt.ylabel()`函数来添加坐标轴标签。 4. 设置坐标轴刻度:可以使用`plt.xticks()`和`plt.yticks()`函数来设置坐标轴的刻度值,并通过`rotation`参数来旋转刻度标签。 5. 添加注释和文本:可以使用`plt.text()`和`plt.annotate()`函数来添加注释和文本,以增加图形的可读性和说明性。 6. 子图布局和图形尺寸:可以使用`plt.subplots()`函数创建包含多个子图的布局,通过`plt.figure()`函数设置图形的尺寸和分辨率。 7. 使用各种图形类型:除了常见的折线图和散点图外,Matplotlib还支持绘制柱状图、饼图、箱线图、等高线图等多种图形类型。 8. 添加背景和网格线:可以使用`plt.grid()`函数来添加网格线,使用`plt.axhspan()`和`plt.axvspan()`函数来添加背景色。 9. 保存和导出图形:通过`plt.savefig()`函数可以将图形保存为常见的图像格式,如PNG、JPEG等。 10. 添加动画效果:使用Matplotlib的`animation`模块可以创建动画效果,通过逐帧绘制来展示数据的演变过程。 以上是进阶Matplotlib的一些常用代码示例,通过了解和运用这些功能,可以更加灵活地使用Matplotlib库来绘制专业水平的数据可视化图形。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值