绘图窗口不显示在matplotlib 绘图问题,怎么解决

最近在看《Python数据分析》这本书,而自己写代码一直用的是Pycharm,在练习的时候就碰到了plot()绘图不能显示出来的问题。网上翻了一下找到知乎上一篇回答,试了一下好像不行,而且答住提供的“from pylab import *”的方法也不太符合编程规范,最后在Stackoverflow找到了想要的答案,特在此分析一下给大家:
以下是有问题的代码,不能绘图成功:
import pandas as pd
from numpy import *
import matplotlib.pyplot as plt
ts = pd.Series(random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
解决方案是:导入matplotlib.pyplot库,绘图后再调用matplotlib.pyplot.show()方法就能把绘制的图显示出来了!
如下(注:后面发现此方法在知乎上那篇问答的评论区有人提供了):
import pandas as pd
from numpy import *
import matplotlib.pyplot as plt
ts = pd.Series(random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.show()
本文已收录于以下专栏:
相关文章推荐
对以下数据画图结果图不显示,修改过程如下df3 = {'chinese':109, 'American':88, 'German': 66, 'Korea':23, 'Japan':5, 'Engla...
我的环境是centos6.3默认有个python2.6,自己又装了个python2.7版本,
matplotlib 使用show()无法显示,从网上各种查找问题,发现自带的python2.6版本可以显...
网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。
最近,我重新安装了ubuntu,使用virtualenv安装了matplotlib。然后,问题来了。当我运行下列代码时,没有图框跳出来。
import matplotlib.pyplot as ...
最近用了pycharm,感觉还不错,就是pandas中Series、DataFrame的plot()方法不显示图片就给我结束了,但是我在ipython里就能画图
以前的代码是这样的
import ...
快乐虾http://blog.csdn.net/lights_joy/(QQ群:Visual EmbedLinux Tools )欢迎转载,但请保留作者信息1.    OpenCV图...
http://blog.csdn.net/pipisorry/article/details/matplotlib介绍        matplotlib 是python最著名的绘图库...
转载自:Segment Fault
本文作为学习过程中对matplotlib一些常用知识点的整理,方便查找。
强烈推荐ipython
无论你工作在什么项目上,IPython都是值得推荐的。利用i...
实际上前面我们就已经用到了图像的绘制,如:
io.imshow(img)  
这一行代码的实质是利用matplotlib包对图片进行绘制,绘制成功后,返回一个matplotlib类型的数据。因此,...
使用Python的Matplotlib的时候,很多任务是批处理的,
中间需要画图,并保存图像,可是不希望每次都把图形显示出来,
可以试一下下面的脚本testplot.py:
import num...
在数据挖掘、数据分析领域里面,经常需要对处理后得到的数据进行可视化的呈现,这是一种更为直观、更为清晰的表达方式,让接受者可以更加直观的把握整体数据的分布或者走向等信息。在linux系统下使用pytho...
他的最新文章
讲师:董西成
讲师:唐宇迪
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)【Matplotlib】绘图常见设置说明
设置1:图像的大小设置。
如果已经存在figure对象,可以通过以下代码设置尺寸大小:
f.set_figheight(15)
f.set_figwidth(15)
若果通过.sublots()命令来创建新的figure对象,
可以通过设置figsize参数达到目的。
f, axs = plt.subplots(2,2,figsize=(15,15))
设置2:刻度和标注特殊设置
描述如下:在X轴标出一些重要的刻度点,当然实现方式有两种:直接在X轴上标注和通过注释annotate的形式标注在合适的位置。
其中第一种的实现并不是很合适,此处为了学习的目的一并说明下。
先说第一种:
正常X轴标注不会是这样的,为了说明此问题特意标注成这样,如此看来 0.3 和
0.4的标注重叠了,当然了解决重叠的问题可以通过改变figure&的size实现,显然此处并不想这样做。
怎么解决呢,那就在 0.3 和 0.4之间再设置一个刻度,有了空间后不显示即可。
代码如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(3, 3))
ax = fig.add_subplot(1, 1, 1, frameon=False)
ax.set_xlim(-0.015, 1.515)
ax.set_ylim(-0.01, 1.01)
ax.set_xticks([0, 0.3, 0.4, 1.0, 1.5])
#增加0.35处的刻度并不标注文本,然后重新标注0.3和0.4处文本
ax.set_xticklabels([0.0, "", "", 1.0, 1.5])
ax.set_xticks([0.35], minor=True)
ax.set_xticklabels(["0.3 0.4"], minor=True)
#上述设置只是增加空间,并不想看到刻度的标注,因此次刻度线不予显示。
for line in ax.xaxis.get_minorticklines():
line.set_visible(False)
ax.grid(True)
plt.show()
最终图像形式如下:
当然最合理的方式是采用注释的形式,比如:
代码如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
# Plot a sinc function
x=np.linspace(-10,10,100)
y=np.sinc(x-delta)
# Mark delta
plt.axvline(delta,ls="--",color="r")
plt.annotate(r"$\delta$",xy=(delta+0.2,-0.2),color="r",size=15)
plt.plot(x,y)
设置3:增加X轴与Y轴间的间隔,向右移动X轴标注一点点即可
显示效果对比:
两张的图像的差别很明显,代码如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
plot_data=[1.7,1.7,1.7,1.54,1.52]
xdata = range(len(plot_data))
labels = ["2009-June","2009-Dec","2010-June","2010-Dec","2011-June"]
ax.plot(xdata,plot_data,"b-")
ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels)
ax.set_yticks([1.4,1.6,1.8])
# grow the y axis down by 0.05
ax.set_ylim(1.35, 1.8)
# expand the x axis by 0.5 at two ends
ax.set_xlim(-0.5, len(labels)-0.5)
plt.show()
设置4:移动刻度标注
上图说明需求:
通过设置&来控制标注的左右位置:
for tick in ax2.xaxis.get_majorticklabels():
tick.set_horizontalalignment("left")
当然标注文本的上下位置也是可以控制的,比如:
ax2.xaxis.get_majorticklabels()[2].set_y(-.1)
当然控制刻度标注的上下位置也可以用labelpad参数进行设置:
pl.xlabel("...", labelpad=20)
ax.xaxis.labelpad = 20
具体设置请查阅官方文档,完整的代码如下:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import datetime
# my fake data
dates = np.array([datetime.datetime(2000,1,1) + datetime.timedelta(days=i) for i in range(365*5)])
data = np.sin(np.arange(365*5)/365.0*2*np.pi - 0.25*np.pi) + np.random.rand(365*5) /3
# creates fig with 2 subplots
fig = plt.figure(figsize=(10.0, 6.0))
ax = plt.subplot2grid((2,1), (0, 0))
ax2 = plt.subplot2grid((2,1), (1, 0))
## plot dates
ax2.plot_date( dates, data )
# rotates labels
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=-45 )
# shift labels to the right
for tick in ax2.xaxis.get_majorticklabels():
tick.set_horizontalalignment("right")
plt.tight_layout()
plt.show()
设置5:调整图像边缘及图像间的空白间隔
图像外部边缘的调整可以使用plt.tight_layout()进行自动控制,此方法不能够很好的控制图像间的间隔。
如果想同时控制图像外侧边缘以及图像间的空白区域,使用命令:
plt.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8,hspace=0.2, wspace=0.3)
设置6:子图像统一标题设置。
效果如下(subplot row i):
思路其实创建整个的子图像,然后将图像的刻度、标注等部分作不显示设置,仅仅显示图像的 title。
代码如下:
import matplotlib.pyplot as plt
fig, big_axes = plt.subplots(figsize=(15.0, 15.0) , nrows=3, ncols=1, sharey=True)
for row, big_ax in enumerate(big_axes, start=1):
big_ax.set_title("Subplot row %s \n" % row, fontsize=16)
# Turn off axis lines and ticks of the big subplot
# obs alpha is 0 in RGBA string!
big_ax.tick_params(labelcolor=(0,0,0,0), top='off', bottom='off', left='off', right='off')
# removes the white frame
big_ax._frameon = False
for i in range(1,10):
ax = fig.add_subplot(3,3,i)
ax.set_title('Plot title ' + str(i))
fig.set_facecolor('w')
plt.tight_layout()
plt.show()
设置7:图像中标记线和区域的绘制
效果如下:
代码如下:
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(-1, 2, .01)
s = np.sin(2*np.pi*t)
plt.plot(t, s)
# draw a thick red hline at y=0 that spans the xrange
l = plt.axhline(linewidth=4, color='r')
# draw a default hline at y=1 that spans the xrange
l = plt.axhline(y=1)
# draw a default vline at x=1 that spans the yrange
l = plt.axvline(x=1)
# draw a thick blue vline at x=0 that spans the upper quadrant of
# the yrange
l = plt.axvline(x=0, ymin=0.75, linewidth=4, color='b')
# draw a default hline at y=.5 that spans the middle half of
# the axes
l = plt.axhline(y=.5, xmin=0.25, xmax=0.75)
p = plt.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
p = plt.axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
plt.axis([-1, 2, -1, 2])
plt.show()
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。windows使用anaconda中的spyder,将ipython作为代码解释器
使用matplotlib中的pylab绘图时,在%matplotlib inline模式下中文显示方框
问题分析:
默认使用自带的字体,无法使用系统的其他字体,而自带字体库中缺省中文字体
解决方法:
进入anaconda安装目录下的Lib\site-packages\matplotlib\mpl-data
打开matplotlibrc文件,删除font.family、font.sans-serif(axes.unicode_minus貌似不必要)前面的#
上述文件中相应行修改后的结果如下所示,xx为中文字体名,其后的字体不修改。
font.family
: sans-serif
font.sans-serif
: xx, Bitstream Vera Sans, Lucida Grande...
axes.unicode_minus
重启Spyder或者是重新启动console来使更改生效
xx字体名查找规则
到C:\windows\fonts\下找到中文字体文件,文件属性中查看字体文件名,例如仿宋是simfang
打开C:\Users\用户名\.matplotlib/fontList.cache字体索引文件(mac是home目录下),在文件中查找simfang,结果如下
S'FangSong'
VC:\u005cWindows\u005cFonts\u005csimfang.ttf
S'FangSong'中的FangSong即是字体文件对应的字体名,即要添加的xx。(mac下是类似VKaiti SC,其中Kaiti SC是相应的字体名)
字体名查找注意事项
有些字体文件在C:\Users\用户名\.matplotlib/fontList.cache文件中查找不到相应字体名,但添加后在%matplotlib qt模式下显示正常,如Microsoft YaHei
未查找到字体名的字体,可将其字体文件复制到anaconda安装目录\Lib\site-packages\matplotlib\mpl-data\fonts\ttf下,重启Spyder或者是重新启动console来更新fontList.cache
若复制的字体文件是ttc文件则需在matplotlib安装目录下找到font_manager.py文件,在如下代码中添加ttc,删除font_manager.pyc文件,更新fontList.cache
return {'ttf': ('ttf', 'ttc', 'otf'),
'otf': ('ttf', 'otf'),
'afm': ('afm',)}[fontext]
执行以下语句也可重新创建字体索引列表
&&& from matplotlib.font_manager import _rebuild
&&&_rebuild()
最后由 oucb 编辑于日 14:29
闻风观雨,静听无声。让生活与自己都变得有趣I'm running Python v3.5 and matplotlib v1.4.3 on Windows 10 Home. Up to recently, I write the python script using matplotlib with PyQt GUI. The 'plt.show()' code will be written in another module not __main__. When I run this code, Matplotlib figure cannot be moved and exit using red button X at the top of the right side of figure. Strangely, The chart is shown and It really does work well.
Why does this symptom happens? and How can I revise it?
解决方案 I stumbled on a similar problem. This is because your matplotlib figure and your PyQt GUI are both running in the same main thread. Since they are in the main thread, only one of them has the CPU for itself.
I have tried to solve the problem by putting either the PyQT GUI or the matplotlib inside another thread. But that doesn't work. Both PyQT and matplotlib need to run in the main thread.
So here is a workaround. You can start the matplotlib figure from a newly created python shell:
import subprocess
# When you click the button in your PyQT GUI,
# Create a new process:
myMatProcess = subprocess.Popen(['python', 'myGraph.py'], shell=True)
Now your PyQT GUI and the matplotlib figure you're drawing have their own python interpreter shell. And they can run smoothly without blocking each other.
If you have any further questions, don't hesitate to ask. I'd be happy to help you out.
本文地址: &
我在上运行 Python v3.5 和 matplotlib v1.4.3
10首页。直到最近,我使用 matplotlib 和 PyQt
GUI编写python脚本。 ' plt.show()'代码将写入另一个不是 __ main __ 的模块中。当我运行这个代码, Matplotlib图不能移动和退出使用红色按钮X在图右侧的顶部。奇怪的是,图表显示,它真的工作得很好。
为什么会出现这种情况?如何修改它?
解决方案 我偶然发现了一个类似的问题。这是因为你的matplotlib图和你的PyQt GUI都在同一个主线程中运行。因为他们在主线程,只有其中一个有自己的CPU。
我试图解决这个问题,通过放置PyQT GUI或matplotlib内另一个线程。但这不工作。 PyQT和matplotlib都需要在主线程中运行。
这里是一个解决方法。您可以从新创建的python shell启动matplotlib图:
import subprocess
#当你点击你的PyQT GUI中的按钮,#创建一个新的过程: myMatProcess = subprocess.Popen(['python','myGraph.py'],shell = True )
现在你的PyQT GUI和你绘制的matplotlib图有自己的Python解释器shell。
如果您有任何其他问题,请随时与我们联系。我很乐意帮助您。
本文地址: &
扫一扫关注官方微信}

我要回帖

更多关于 matplotlib绘图教程 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信