标签归档:matplotlib

用twinx()辅助轴:如何添加到图例?

问题:用twinx()辅助轴:如何添加到图例?

我有一个使用两个y轴的图twinx()。我还给行加了标签,并想用显示legend(),但我仅成功获得了图例中一个轴的标签:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
ax.legend(loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

因此,我仅获得图例中第一个轴的标签,而没有得到第二个轴的标签“ temp”。如何将第三个标签添加到图例?

在此处输入图片说明

I have a plot with two y-axes, using twinx(). I also give labels to the lines, and want to show them with legend(), but I only succeed to get the labels of one axis in the legend:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
ax.legend(loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

So I only get the labels of the first axis in the legend, and not the label ‘temp’ of the second axis. How could I add this third label to the legend?

enter image description here


回答 0

您可以通过添加以下行轻松添加第二个图例:

ax2.legend(loc=0)

您将获得:

在此处输入图片说明

但是,如果要将所有标签都放在一个图例上,则应执行以下操作:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

fig = plt.figure()
ax = fig.add_subplot(111)

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

这会给你这个:

在此处输入图片说明

You can easily add a second legend by adding the line:

ax2.legend(loc=0)

You’ll get this:

enter image description here

But if you want all labels on one legend then you should do something like this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

fig = plt.figure()
ax = fig.add_subplot(111)

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

Which will give you this:

enter image description here


回答 1

我不确定此功能是否是新功能,但您也可以使用get_legend_handles_labels()方法,而不是自己跟踪行和标签:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

pi = np.pi

# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
        * np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')

# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

I’m not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

pi = np.pi

# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
        * np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')

# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

回答 2

从matplotlib 2.1版开始,您可以使用图例。可以创建一个图例ax.legend(),而不是通过轴的手柄ax生成图例。

fig.legend(loc =“右上”)

它将收集图中所有子图的所有手柄。由于它是一个人物图例,因此它将放置在人物的角上,并且loc参数是相对于人物的。

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10)
y = np.linspace(0,10)
z = np.sin(x/3)**2*98

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, '-', label = 'Quantity 1')

ax2 = ax.twinx()
ax2.plot(x,z, '-r', label = 'Quantity 2')
fig.legend(loc="upper right")

ax.set_xlabel("x [units]")
ax.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2")

plt.show()

在此处输入图片说明

为了将图例放回轴中,可以提供a bbox_to_anchor和a bbox_transform。后者是图例应驻留的轴的轴变换。前者可以是loc轴坐标中给定定义的边的坐标。

fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)

在此处输入图片说明

From matplotlib version 2.1 onwards, you may use a figure legend. Instead of ax.legend(), which produces a legend with the handles from the axes ax, one can create a figure legend

fig.legend(loc="upper right")

which will gather all handles from all subplots in the figure. Since it is a figure legend, it will be placed at the corner of the figure, and the loc argument is relative to the figure.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10)
y = np.linspace(0,10)
z = np.sin(x/3)**2*98

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, '-', label = 'Quantity 1')

ax2 = ax.twinx()
ax2.plot(x,z, '-r', label = 'Quantity 2')
fig.legend(loc="upper right")

ax.set_xlabel("x [units]")
ax.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2")

plt.show()

enter image description here

In order to place the legend back into the axes, one would supply a bbox_to_anchor and a bbox_transform. The latter would be the axes transform of the axes the legend should reside in. The former may be the coordinates of the edge defined by loc given in axes coordinates.

fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)

enter image description here


回答 3

您可以通过在ax中添加行来轻松获得所需的内容:

ax.plot([], [], '-r', label = 'temp')

要么

ax.plot(np.nan, '-r', label = 'temp')

除了给ax图例添加标签之外,这什么都不会绘制。

我认为这是一种简单得多的方法。当第二轴上只有几条线时,无需自动跟踪线,因为像上面这样的手工固定将非常容易。无论如何,这取决于您的需求。

整个代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)

fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()

#---------- look at below -----------

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')

ax2.plot(time, temp, '-r')  # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp')  # Make an agent in ax

ax.legend(loc=0)

#---------------done-----------------

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

情节如下:

在此处输入图片说明


更新:添加更好的版本:

ax.plot(np.nan, '-r', label = 'temp')

plot(0, 0)可能会改变轴范围,但无济于事。


散布的另一个示例

ax.scatter([], [], s=100, label = 'temp')  # Make an agent in ax
ax2.scatter(time, temp, s=10)  # The true scatter in ax2

ax.legend(loc=1, framealpha=1)

You can easily get what you want by adding the line in ax:

ax.plot([], [], '-r', label = 'temp')

or

ax.plot(np.nan, '-r', label = 'temp')

This would plot nothing but add a label to legend of ax.

I think this is a much easier way. It’s not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.

The whole code is as below:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)

fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()

#---------- look at below -----------

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')

ax2.plot(time, temp, '-r')  # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp')  # Make an agent in ax

ax.legend(loc=0)

#---------------done-----------------

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

The plot is as below:

enter image description here


Update: add a better version:

ax.plot(np.nan, '-r', label = 'temp')

This will do nothing while plot(0, 0) may change the axis range.


One extra example for scatter

ax.scatter([], [], s=100, label = 'temp')  # Make an agent in ax
ax2.scatter(time, temp, s=10)  # The true scatter in ax2

ax.legend(loc=1, framealpha=1)

回答 4

可能适合您需求的快速技巧。

取下盒子的框架,然后手动将两个图例彼此相邻放置。像这样

ax1.legend(loc = (.75,.1), frameon = False)
ax2.legend( loc = (.75, .05), frameon = False)

位置元组从左到右和从下到上的百分比代表图表中的位置。

A quick hack that may suit your needs..

Take off the frame of the box and manually position the two legends next to each other. Something like this..

ax1.legend(loc = (.75,.1), frameon = False)
ax2.legend( loc = (.75, .05), frameon = False)

Where the loc tuple is left-to-right and bottom-to-top percentages that represent the location in the chart.


回答 5

我找到了以下官方matplotlib示例,该示例使用host_subplot在一个图例中显示多个y轴和所有不同的标签。无需任何解决方法。到目前为止,我找到的最佳解决方案。 http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
                                    axes=par2,
                                    offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

plt.draw()
plt.show()

I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. No workaround necessary. Best solution I found so far. http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
                                    axes=par2,
                                    offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

plt.draw()
plt.show()

如何使用子图更改图形大小?

问题:如何使用子图更改图形大小?

我在Matplotlib网站上遇到了这个示例。我想知道是否有可能增加数字的大小。

我尝试过

f.figsize(15,15)

但它什么也没做。

I came across this example in the Matplotlib website. I was wondering if it was possible to increase the figure size.

I tried with

f.figsize(15,15)

but it does nothing.


回答 0

如果已经有了图形对象,请使用:

f.set_figheight(15)
f.set_figwidth(15)

但是,如果您使用.subplots()命令(如您所显示的示例中所示)来创建新图形,则还可以使用:

f, axs = plt.subplots(2,2,figsize=(15,15))

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you’re showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

回答 1

或者,figure()使用figsize参数创建一个对象,然后使用add_subplot来添加子图。例如

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

简单的例子

此方法的好处是语法更接近于subplot()而不是的调用subplots()。例如,次要情节似乎没有使用支持GridSpec用于控制次要情节的间距,但都subplot()add_subplot()做的。

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn’t seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.


在python中使用matplotlib绘制对数轴

问题:在python中使用matplotlib绘制对数轴

我想使用matplotlib绘制一个对数轴的图形。

我一直在阅读文档,但无法弄清楚语法。我知道这可能'scale=linear'与plot参数类似,但是我似乎无法正确理解

示例程序:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)
pylab.show()

I want to plot a graph with one logarithmic axis using matplotlib.

I’ve been reading the docs, but can’t figure out the syntax. I know that it’s probably something simple like 'scale=linear' in the plot arguments, but I can’t seem to get it right

Sample program:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)
pylab.show()

回答 0

您可以使用该Axes.set_yscale方法。这样,您可以在Axes创建对象后更改比例。这也将允许您构建一个控件,让用户根据需要选择比例。

要添加的相关行是:

ax.set_yscale('log')

您可以使用'linear'切换回线性刻度。您的代码如下所示:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

pylab.show()

结果图

You can use the Axes.set_yscale method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.

The relevant line to add is:

ax.set_yscale('log')

You can use 'linear' to switch back to a linear scale. Here’s what your code would look like:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

pylab.show()

result chart


回答 1

首先,混合pylabpyplot编码不是很整洁。而且,pyplot样式比使用pylab更为可取

这是一个仅使用pyplot函数的稍作清理的代码:

from matplotlib import pyplot

a = [ pow(10,i) for i in range(10) ]

pyplot.subplot(2,1,1)
pyplot.plot(a, color='blue', lw=2)
pyplot.yscale('log')
pyplot.show()

相关功能是pyplot.yscale()。如果使用面向对象的版本,请用方法替换它Axes.set_yscale()。请记住,您还可以使用pyplot.xscale()(或Axes.set_xscale())更改X轴的比例。

检查我的问题‘log’和’symlog’有什么区别?查看matplotlib提供的图形比例的一些示例。

First of all, it’s not very tidy to mix pylab and pyplot code. What’s more, pyplot style is preferred over using pylab.

Here is a slightly cleaned up code, using only pyplot functions:

from matplotlib import pyplot

a = [ pow(10,i) for i in range(10) ]

pyplot.subplot(2,1,1)
pyplot.plot(a, color='blue', lw=2)
pyplot.yscale('log')
pyplot.show()

The relevant function is pyplot.yscale(). If you use the object-oriented version, replace it by the method Axes.set_yscale(). Remember that you can also change the scale of X axis, using pyplot.xscale() (or Axes.set_xscale()).

Check my question What is the difference between ‘log’ and ‘symlog’? to see a few examples of the graph scales that matplotlib offers.


回答 2

您只需要使用符号学而不是情节:

from pylab import *
import matplotlib.pyplot  as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)

line, = ax.semilogy(a, color='blue', lw=2)
show()

You simply need to use semilogy instead of plot:

from pylab import *
import matplotlib.pyplot  as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)

line, = ax.semilogy(a, color='blue', lw=2)
show()

回答 3

如果要更改对数的底数,只需添加:

plt.yscale('log',basey=2) 
# where basex or basey are the bases of log

if you want to change the base of logarithm, just add:

plt.yscale('log',basey=2) 
# where basex or basey are the bases of log

回答 4

我知道这有点不合时宜,因为一些评论提到这ax.set_yscale('log')是“最好的”解决方案,我认为可能是反驳。我不建议将其ax.set_yscale('log')用于直方图和条形图。在我的版本(0.99.1.1)中,我遇到了一些渲染问题-不确定此问题的普遍性。但是,bar和hist都具有可选参数,可以将y比例设置为log,这很好用。

参考:http : //matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist

I know this is slightly off-topic, since some comments mentioned the ax.set_yscale('log') to be “nicest” solution I thought a rebuttal could be due. I would not recommend using ax.set_yscale('log') for histograms and bar plots. In my version (0.99.1.1) i run into some rendering problems – not sure how general this issue is. However both bar and hist has optional arguments to set the y-scale to log, which work fine.

references: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist


回答 5

因此,如果您只是像我经常那样使用简单的API(我在ipython中经常使用它),那么这很简单

yscale('log')
plot(...)

希望这可以帮助寻找简单答案的人!:)。

So if you are simply using the unsophisticated API, like I often am (I use it in ipython a lot), then this is simply

yscale('log')
plot(...)

Hope this helps someone looking for a simple answer! :).


回答 6

您可以使用以下代码:

np.log(df['col_whose_log_you_need']).iplot(kind='histogram', bins=100,
                                   xTitle = 'log of col',yTitle ='Count corresponding to column',
                                   title='Distribution of log(col_whose_log_you_need)')

You can use below code:

np.log(df['col_whose_log_you_need']).iplot(kind='histogram', bins=100,
                                   xTitle = 'log of col',yTitle ='Count corresponding to column',
                                   title='Distribution of log(col_whose_log_you_need)')

在Matplotlib图中隐藏轴文本

问题:在Matplotlib图中隐藏轴文本

我正在尝试在两个轴上绘制一个没有刻度或数字的图形(我使用传统意义上的轴,而不是matplotlib命名法!)。我遇到的一个问题是matplotlib通过减去值N来调整x(y)ticklabel,然后在轴的末端添加N。

这可能含糊其词,但以下简化示例突出了该问题,其中“ 6.18”是N的有问题的值:

import matplotlib.pyplot as plt
import random
prefix = 6.18

rx = [prefix+(0.001*random.random()) for i in arange(100)]
ry = [prefix+(0.001*random.random()) for i in arange(100)]
plt.plot(rx,ry,'ko')

frame1 = plt.gca()
for xlabel_i in frame1.axes.get_xticklabels():
    xlabel_i.set_visible(False)
    xlabel_i.set_fontsize(0.0)
for xlabel_i in frame1.axes.get_yticklabels():
    xlabel_i.set_fontsize(0.0)
    xlabel_i.set_visible(False)
for tick in frame1.axes.get_xticklines():
    tick.set_visible(False)
for tick in frame1.axes.get_yticklines():
    tick.set_visible(False)

plt.show()

我想知道的三件事是:

  1. 如何关闭这一行为在首位(虽然在大多数情况下,它是有用的,它并不总是!)我已经通过看matplotlib.axis.XAxis,并不能找到任何合适

  2. 如何使N消失(即X.set_visible(False)

  3. 无论如何,还有更好的方法来做上述事情吗?如果可以的话,我的最终绘图将是图中的4×4子图。

I’m trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.

This may be vague, but the following simplified example highlights the issue, with ‘6.18’ being the offending value of N:

import matplotlib.pyplot as plt
import random
prefix = 6.18

rx = [prefix+(0.001*random.random()) for i in arange(100)]
ry = [prefix+(0.001*random.random()) for i in arange(100)]
plt.plot(rx,ry,'ko')

frame1 = plt.gca()
for xlabel_i in frame1.axes.get_xticklabels():
    xlabel_i.set_visible(False)
    xlabel_i.set_fontsize(0.0)
for xlabel_i in frame1.axes.get_yticklabels():
    xlabel_i.set_fontsize(0.0)
    xlabel_i.set_visible(False)
for tick in frame1.axes.get_xticklines():
    tick.set_visible(False)
for tick in frame1.axes.get_yticklines():
    tick.set_visible(False)

plt.show()

The three things I would like to know are:

  1. How to turn off this behaviour in the first place (although in most cases it is useful, it is not always!) I have looked through matplotlib.axis.XAxis and cannot find anything appropriate

  2. How can I make N disappear (i.e. X.set_visible(False))

  3. Is there a better way to do the above anyway? My final plot would be 4×4 subplots in a figure, if that is relevant.


回答 0

除了隐藏每个元素,您还可以隐藏整个轴:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

或者,您可以将刻度线设置为空列表:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

在第二个选项中,您仍然可以使用plt.xlabel()plt.ylabel()在轴上添加标签。

Instead of hiding each element, you can hide the whole axis:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

Or, you can set the ticks to an empty list:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.


回答 1

如果要仅隐藏保留网格线的轴文本:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

set_visible(False)set_ticks([])也将隐藏网格线。

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.


回答 2

如果您像我一样,并且ax在绘制图形时并不总是检索轴,则一个简单的解决方案是

plt.xticks([])
plt.yticks([])

If you are like me and don’t always retrieve the axes, ax, when plotting the figure, then a simple solution would be to do

plt.xticks([])
plt.yticks([])

回答 3

有点旧的线程,但是,这似乎是使用最新版本的matplotlib的更快方法:

设置x轴的主要格式

ax.xaxis.set_major_formatter(plt.NullFormatter())

Somewhat of an old thread but, this seems to be a faster method using the latest version of matplotlib:

set the major formatter for the x-axis

ax.xaxis.set_major_formatter(plt.NullFormatter())

回答 4

我实际上无法根据此处的任何代码段(甚至答案中接受的代码段)绘制没有边界或轴数据的图像。在浏览了一些API文档之后,我使用了这段代码来渲染图像

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

我使用该tick_params调用基本上关闭了可能呈现的任何其他信息,并且在输出文件中有一个完美的图形。

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.


回答 5

我已经对该图进行了颜色编码以简化此过程。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

在此处输入图片说明

您可以使用以下命令完全控制图形,以完成答案,我还添加了对样条线的控制:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)

# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)

I’ve colour coded this figure to ease the process.

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

enter image description here

You can have full control over the figure using these commands, to complete the answer I’ve add also the control over the splines:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)

# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)

回答 6

使用面向对象的API时,该Axes对象有两种用于删除轴文本的有用方法,set_xticklabels()set_xticks()

假设您使用

fig, ax = plt.subplots(1)
ax.plot(x, y)

如果您只想删除刻度线标签,则可以使用

ax.set_xticklabels([])

或完全删除刻度线,您可以使用

ax.set_xticks([])

这些方法对于准确指定刻度线的位置以及如何标记刻度线很有用。传递空列表将分别导致没有滴答声或标签。

When using the object oriented API, the Axes object has two useful methods for removing the axis text, set_xticklabels() and set_xticks().

Say you create a plot using

fig, ax = plt.subplots(1)
ax.plot(x, y)

If you simply want to remove the tick labels, you could use

ax.set_xticklabels([])

or to remove the ticks completely, you could use

ax.set_xticks([])

These methods are useful for specifying exactly where you want the ticks and how you want them labeled. Passing an empty list results in no ticks, or no labels, respectively.


回答 7

一种技巧可能是将刻度标签的颜色设置为白色以隐藏它!

plt.xticks(color='w')
plt.yticks(color='w')

One trick could be setting the color of tick labels as white to hide it!

plt.xticks(color='w')
plt.yticks(color='w')

如何使用matplotlib.pyplot更改图例大小

问题:如何使用matplotlib.pyplot更改图例大小

这里有一个简单的问题:我试图使用matplotlib.pyplot较小的图例(即,文本较小)。我正在使用的代码是这样的:

plot.figure()
plot.scatter(k, sum_cf, color='black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0],  color='b', label='Dis 1: cf = .6, var = .2')
plot.scatter(k, data[:, 1],  color='r',  label='Dis 2: cf = .2, var = .1')
plot.scatter(k, data[:, 2],  color='g', label='Dis 3: cf = .1, var = .01')
plot.legend(loc=2)

Simple question here: I’m trying to get the size of my legend using matplotlib.pyplot to be smaller (i.e., the text to be smaller). The code I’m using goes something like this:

plot.figure()
plot.scatter(k, sum_cf, color='black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0],  color='b', label='Dis 1: cf = .6, var = .2')
plot.scatter(k, data[:, 1],  color='r',  label='Dis 2: cf = .2, var = .1')
plot.scatter(k, data[:, 2],  color='g', label='Dis 3: cf = .1, var = .01')
plot.legend(loc=2)

回答 0

您可以通过调整prop关键字为图例设置单独的字体大小。

plot.legend(loc=2, prop={'size': 6})

这需要对应于matplotlib.font_manager.FontProperties属性的关键字字典。请参阅说明文件的文档

关键字参数:

prop: [ None | FontProperties | dict ]
    A matplotlib.font_manager.FontProperties instance. If prop is a 
    dictionary, a new instance will be created with prop. If None, use
    rc settings.

1.2.1版开始,也可以使用关键字fontsize

You can set an individual font size for the legend by adjusting the prop keyword.

plot.legend(loc=2, prop={'size': 6})

This takes a dictionary of keywords corresponding to matplotlib.font_manager.FontProperties properties. See the documentation for legend:

Keyword arguments:

prop: [ None | FontProperties | dict ]
    A matplotlib.font_manager.FontProperties instance. If prop is a 
    dictionary, a new instance will be created with prop. If None, use
    rc settings.

It is also possible, as of version 1.2.1, to use the keyword fontsize.


回答 1

这应该做

import pylab as plot
params = {'legend.fontsize': 20,
          'legend.handlelength': 2}
plot.rcParams.update(params)

然后再做图。

还有很多其他rcParam,它们也可以在matplotlibrc文件中设置。

大概还可以通过matplotlib.font_manager.FontProperties实例更改它,但是我不知道该怎么做。->请参阅Yann的答案。

This should do

import pylab as plot
params = {'legend.fontsize': 20,
          'legend.handlelength': 2}
plot.rcParams.update(params)

Then do the plot afterwards.

There are a ton of other rcParams, they can also be set in the matplotlibrc file.

Also presumably you can change it passing a matplotlib.font_manager.FontProperties instance but this I don’t know how to do. –> see Yann’s answer.


回答 2

使用 import matplotlib.pyplot as plt

方法1:调用图例时指定字体大小(重复)

plt.legend(fontsize=20) # using a size in points
plt.legend(fontsize="x-large") # using a named size

使用此方法,您可以在创建时为每个图例设置字体大小(允许您拥有多个具有不同字体大小的图例)。但是,每次创建图例时,都必须手动键入所有内容。

(注意:@ Mathias711在他的答案中列出了可用的命名字体大小)

方法2:在rcParams中指定字体大小(方便)

plt.rc('legend',fontsize=20) # using a size in points
plt.rc('legend',fontsize='medium') # using a named size

使用此方法,您可以设置默认的图例字体大小,除非使用方法1另行指定,否则所有图例将自动使用该字体。这意味着您可以在代码开头设置图例字体大小,而不必担心为每个图例设置它。

如果你使用了一个名为大小例如'medium',那么传说中的文本将与全球规模font.sizercParams。改变font.size用途plt.rc(font.size='medium')

using import matplotlib.pyplot as plt

Method 1: specify the fontsize when calling legend (repetitive)

plt.legend(fontsize=20) # using a size in points
plt.legend(fontsize="x-large") # using a named size

With this method you can set the fontsize for each legend at creation (allowing you to have multiple legends with different fontsizes). However, you will have to type everything manually each time you create a legend.

(Note: @Mathias711 listed the available named fontsizes in his answer)

Method 2: specify the fontsize in rcParams (convenient)

plt.rc('legend',fontsize=20) # using a size in points
plt.rc('legend',fontsize='medium') # using a named size

With this method you set the default legend fontsize, and all legends will automatically use that unless you specify otherwise using method 1. This means you can set your legend fontsize at the beginning of your code, and not worry about setting it for each individual legend.

If you use a named size e.g. 'medium', then the legend text will scale with the global font.size in rcParams. To change font.size use plt.rc(font.size='medium')


回答 3

除了点的大小,还有一些命名的fontsizes

xx-small
x-small
small
medium
large
x-large
xx-large

用法:

pyplot.legend(loc=2, fontsize = 'x-small')

There are also a few named fontsizes, apart from the size in points:

xx-small
x-small
small
medium
large
x-large
xx-large

Usage:

pyplot.legend(loc=2, fontsize = 'x-small')

回答 4

有多种设置可用于调整图例大小。我发现最有用的两个是:

  • labelspacing:以字体大小的倍数设置标签条目之间的间距。例如使用10磅字体,legend(..., labelspacing=0.2)会将条目之间的间距减少到2点。我安装的默认值约为0.5。
  • prop:可以完全控制字体大小等。您可以使用设置8点字体legend(..., prop={'size':8})。我安装的默认值约为14点。

此外,图例的文档列出了许多其他填充的和间隔的参数,包括:borderpadhandlelengthhandletextpadborderaxespad,和columnspacing。这些都遵循相同的格式,与labelspacing和area相同,也是fontsize的倍数。

也可以使用matplotlibrc文件将这些值设置为所有图形的默认值。

There are multiple settings for adjusting the legend size. The two I find most useful are:

  • labelspacing: which sets the spacing between label entries in multiples of the font size. For instance with a 10 point font, legend(..., labelspacing=0.2) will reduce the spacing between entries to 2 points. The default on my install is about 0.5.
  • prop: which allows full control of the font size, etc. You can set an 8 point font using legend(..., prop={'size':8}). The default on my install is about 14 points.

In addition, the legend documentation lists a number of other padding and spacing parameters including: borderpad, handlelength, handletextpad, borderaxespad, and columnspacing. These all follow the same form as labelspacing and area also in multiples of fontsize.

These values can also be set as the defaults for all figures using the matplotlibrc file.


回答 5

在我的安装中,FontProperties仅更改文本大小,但它仍然太大且间隔开。我在pyplot.rcParams:中找到了一个参数legend.labelspacing,我猜它被设置为字体大小的一小部分。我已经改变了

pyplot.rcParams.update({'legend.labelspacing':0.25})

我不确定如何将其指定给pyplot.legend函数-传递

prop={'labelspacing':0.25}

要么

prop={'legend.labelspacing':0.25}

返回错误。

On my install, FontProperties only changes the text size, but it’s still too large and spaced out. I found a parameter in pyplot.rcParams: legend.labelspacing, which I’m guessing is set to a fraction of the font size. I’ve changed it with

pyplot.rcParams.update({'legend.labelspacing':0.25})

I’m not sure how to specify it to the pyplot.legend function – passing

prop={'labelspacing':0.25}

or

prop={'legend.labelspacing':0.25}

comes back with an error.


回答 6

plot.legend(loc =’右下角’,decimal_places = 2,fontsize =’11’,title =’嘿’,title_fontsize =’20’)

plot.legend(loc = ‘lower right’, decimal_places = 2, fontsize = ’11’, title = ‘Hey there’, title_fontsize = ’20’)


如何在Matplotlib图上更改字体大小

问题:如何在Matplotlib图上更改字体大小

如何更改matplotlib图上所有元素(刻度,标签,标题)的字体大小?

我知道如何更改刻度标签的大小,方法是:

import matplotlib 
matplotlib.rc('xtick', labelsize=20) 
matplotlib.rc('ytick', labelsize=20) 

但是如何改变其余的呢?

How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot?

I know how to change the tick label sizes, this is done with:

import matplotlib 
matplotlib.rc('xtick', labelsize=20) 
matplotlib.rc('ytick', labelsize=20) 

But how does one change the rest?


回答 0

matplotlib文档中

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

matplotlib.rc('font', **font)

这会将所有项目的字体设置为kwargs对象指定的字体font

另外,您也可以使用此答案中rcParams update建议的方法:

matplotlib.rcParams.update({'font.size': 22})

要么

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})

您可以在“ 定制matplotlib”页面上找到可用属性的完整列表。

From the matplotlib documentation,

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

matplotlib.rc('font', **font)

This sets the font of all items to the font specified by the kwargs object, font.

Alternatively, you could also use the rcParams update method as suggested in this answer:

matplotlib.rcParams.update({'font.size': 22})

or

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})

You can find a full list of available properties on the Customizing matplotlib page.


回答 1

如果您是像我这样的控制狂,则可能需要显式设置所有字体大小:

import matplotlib.pyplot as plt

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

请注意,您还可以设置在以下位置调用rc方法的大小matplotlib

import matplotlib

SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)

# and so on ...

If you are a control freak like me, you may want to explicitly set all your font sizes:

import matplotlib.pyplot as plt

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

Note that you can also set the sizes calling the rc method on matplotlib:

import matplotlib

SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)

# and so on ...

回答 2

matplotlib.rcParams.update({'font.size': 22})
matplotlib.rcParams.update({'font.size': 22})

回答 3

如果要仅更改已创建的特定图的字体大小,请尝试以下操作:

import matplotlib.pyplot as plt

ax = plt.subplot(111, xlabel='x', ylabel='y', title='title')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
             ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(20)

If you want to change the fontsize for just a specific plot that has already been created, try this:

import matplotlib.pyplot as plt

ax = plt.subplot(111, xlabel='x', ylabel='y', title='title')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
             ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(20)

回答 4

更新:请参阅答案的底部以获取一种更好的方法。
更新#2:我也想出了更改图例标题字体。
更新#3:Matplotlib 2.0.0中存在一个错误,错误导致对数轴的刻度标签恢复为默认字体。应该在2.0.1中修复,但是我已经在答案的第二部分中包含了解决方法。

此答案适用于试图更改所有字体(包括图例)的任何人,以及适用于每件事使用不同字体和大小的任何人。它不使用rc(对我来说似乎不起作用)。这相当麻烦,但是我个人无法使用任何其他方法。它基本上将ryggyr的答案与SO的其他答案结合在一起。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

# Set the font dictionaries (for plot title and axis titles)
title_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',
              'verticalalignment':'bottom'} # Bottom vertical alignment for more space
axis_font = {'fontname':'Arial', 'size':'14'}

# Set the font properties (for use in legend)   
font_path = 'C:\Windows\Fonts\Arial.ttf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)

ax = plt.subplot() # Defines ax variable by creating an empty plot

# Set the tick labels font
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontname('Arial')
    label.set_fontsize(13)

x = np.linspace(0, 10)
y = x + np.random.normal(x) # Just simulates some data

plt.plot(x, y, 'b+', label='Data points')
plt.xlabel("x axis", **axis_font)
plt.ylabel("y axis", **axis_font)
plt.title("Misc graph", **title_font)
plt.legend(loc='lower right', prop=font_prop, numpoints=1)
plt.text(0, 0, "Misc text", **title_font)
plt.show()

这种方法的好处是,通过使用多个字体字典,您可以为各种标题选择不同的字体/大小/粗细/颜色,为刻度标签选择字体,并为图例选择字体,所有这些都是独立的。


更新:

我已经设计出一种略有不同,不太混乱的方法,该方法消除了字体词典,并允许系统上的任何字体,甚至.otf字体。有单独字体的每一件事情,只写更多font_pathfont_prop变量一样。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import matplotlib.ticker
# Workaround for Matplotlib 2.0.0 log axes bug https://github.com/matplotlib/matplotlib/issues/8017 :
matplotlib.ticker._mathdefault = lambda x: '\\mathdefault{%s}'%x 

# Set the font properties (can use more variables for more fonts)
font_path = 'C:\Windows\Fonts\AGaramondPro-Regular.otf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)

ax = plt.subplot() # Defines ax variable by creating an empty plot

# Define the data to be plotted
x = np.linspace(0, 10)
y = x + np.random.normal(x)
plt.plot(x, y, 'b+', label='Data points')

for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font_prop)
    label.set_fontsize(13) # Size here overrides font_prop

plt.title("Exponentially decaying oscillations", fontproperties=font_prop,
          size=16, verticalalignment='bottom') # Size here overrides font_prop
plt.xlabel("Time", fontproperties=font_prop)
plt.ylabel("Amplitude", fontproperties=font_prop)
plt.text(0, 0, "Misc text", fontproperties=font_prop)

lgd = plt.legend(loc='lower right', prop=font_prop) # NB different 'prop' argument for legend
lgd.set_title("Legend", prop=font_prop)

plt.show()

希望这是一个全面的答案

Update: See the bottom of the answer for a slightly better way of doing it.
Update #2: I’ve figured out changing legend title fonts too.
Update #3: There is a bug in Matplotlib 2.0.0 that’s causing tick labels for logarithmic axes to revert to the default font. Should be fixed in 2.0.1 but I’ve included the workaround in the 2nd part of the answer.

This answer is for anyone trying to change all the fonts, including for the legend, and for anyone trying to use different fonts and sizes for each thing. It does not use rc (which doesn’t seem to work for me). It is rather cumbersome but I could not get to grips with any other method personally. It basically combines ryggyr’s answer here with other answers on SO.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

# Set the font dictionaries (for plot title and axis titles)
title_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',
              'verticalalignment':'bottom'} # Bottom vertical alignment for more space
axis_font = {'fontname':'Arial', 'size':'14'}

# Set the font properties (for use in legend)   
font_path = 'C:\Windows\Fonts\Arial.ttf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)

ax = plt.subplot() # Defines ax variable by creating an empty plot

# Set the tick labels font
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontname('Arial')
    label.set_fontsize(13)

x = np.linspace(0, 10)
y = x + np.random.normal(x) # Just simulates some data

plt.plot(x, y, 'b+', label='Data points')
plt.xlabel("x axis", **axis_font)
plt.ylabel("y axis", **axis_font)
plt.title("Misc graph", **title_font)
plt.legend(loc='lower right', prop=font_prop, numpoints=1)
plt.text(0, 0, "Misc text", **title_font)
plt.show()

The benefit of this method is that, by having several font dictionaries, you can choose different fonts/sizes/weights/colours for the various titles, choose the font for the tick labels, and choose the font for the legend, all independently.


UPDATE:

I have worked out a slightly different, less cluttered approach that does away with font dictionaries, and allows any font on your system, even .otf fonts. To have separate fonts for each thing, just write more font_path and font_prop like variables.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import matplotlib.ticker
# Workaround for Matplotlib 2.0.0 log axes bug https://github.com/matplotlib/matplotlib/issues/8017 :
matplotlib.ticker._mathdefault = lambda x: '\\mathdefault{%s}'%x 

# Set the font properties (can use more variables for more fonts)
font_path = 'C:\Windows\Fonts\AGaramondPro-Regular.otf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)

ax = plt.subplot() # Defines ax variable by creating an empty plot

# Define the data to be plotted
x = np.linspace(0, 10)
y = x + np.random.normal(x)
plt.plot(x, y, 'b+', label='Data points')

for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font_prop)
    label.set_fontsize(13) # Size here overrides font_prop

plt.title("Exponentially decaying oscillations", fontproperties=font_prop,
          size=16, verticalalignment='bottom') # Size here overrides font_prop
plt.xlabel("Time", fontproperties=font_prop)
plt.ylabel("Amplitude", fontproperties=font_prop)
plt.text(0, 0, "Misc text", fontproperties=font_prop)

lgd = plt.legend(loc='lower right', prop=font_prop) # NB different 'prop' argument for legend
lgd.set_title("Legend", prop=font_prop)

plt.show()

Hopefully this is a comprehensive answer


回答 5

这是一种完全不同的方法,可以很好地更改字体大小:

更改图形大小

我通常使用这样的代码:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)

较小你做图的大小,更大的字体是相对于情节。这也会放大标记。注意我还设置了dpi每英寸或点。我是从张贴AMTA(美国美国建模老师)论坛上学到的。上面的代码示例:在此处输入图片说明

Here is a totally different approach that works surprisingly well to change the font sizes:

Change the figure size!

I usually use code like this:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)

The smaller you make the figure size, the larger the font is relative to the plot. This also upscales the markers. Note I also set the dpi or dot per inch. I learned this from a posting the AMTA (American Modeling Teacher of America) forum. Example from above code: enter image description here


回答 6

采用 plt.tick_params(labelsize=14)

Use plt.tick_params(labelsize=14)


回答 7

您可以使用plt.rcParams["font.size"]设置font_sizematplotlib,你也可以使用plt.rcParams["font.family"]设置font_familymatplotlib。试试这个例子:

import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')

label = [1,2,3,4,5,6,7,8]
x = [0.001906,0.000571308,0.0020305,0.0037422,0.0047095,0.000846667,0.000819,0.000907]
y = [0.2943301,0.047778308,0.048003167,0.1770876,0.532489833,0.024611333,0.157498667,0.0272095]


plt.ylabel('eigen centrality')
plt.xlabel('betweenness centrality')
plt.text(0.001906, 0.2943301, '1 ', ha='right', va='center')
plt.text(0.000571308, 0.047778308, '2 ', ha='right', va='center')
plt.text(0.0020305, 0.048003167, '3 ', ha='right', va='center')
plt.text(0.0037422, 0.1770876, '4 ', ha='right', va='center')
plt.text(0.0047095, 0.532489833, '5 ', ha='right', va='center')
plt.text(0.000846667, 0.024611333, '6 ', ha='right', va='center')
plt.text(0.000819, 0.157498667, '7 ', ha='right', va='center')
plt.text(0.000907, 0.0272095, '8 ', ha='right', va='center')
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = "50"
plt.plot(x, y, 'o', color='blue')

You can use plt.rcParams["font.size"] for setting font_size in matplotlib and also you can use plt.rcParams["font.family"] for setting font_family in matplotlib. Try this example:

import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')

label = [1,2,3,4,5,6,7,8]
x = [0.001906,0.000571308,0.0020305,0.0037422,0.0047095,0.000846667,0.000819,0.000907]
y = [0.2943301,0.047778308,0.048003167,0.1770876,0.532489833,0.024611333,0.157498667,0.0272095]


plt.ylabel('eigen centrality')
plt.xlabel('betweenness centrality')
plt.text(0.001906, 0.2943301, '1 ', ha='right', va='center')
plt.text(0.000571308, 0.047778308, '2 ', ha='right', va='center')
plt.text(0.0020305, 0.048003167, '3 ', ha='right', va='center')
plt.text(0.0037422, 0.1770876, '4 ', ha='right', va='center')
plt.text(0.0047095, 0.532489833, '5 ', ha='right', va='center')
plt.text(0.000846667, 0.024611333, '6 ', ha='right', va='center')
plt.text(0.000819, 0.157498667, '7 ', ha='right', va='center')
plt.text(0.000907, 0.0272095, '8 ', ha='right', va='center')
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = "50"
plt.plot(x, y, 'o', color='blue')

回答 8

这是我在Jupyter Notebook中通常使用的内容:

# Jupyter Notebook settings

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
%autosave 0
%matplotlib inline
%load_ext autoreload
%autoreload 2

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"


# Imports for data analysis
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 2500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_colwidth', 2000)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)

#size=25
size=15
params = {'legend.fontsize': 'large',
          'figure.figsize': (20,8),
          'axes.labelsize': size,
          'axes.titlesize': size,
          'xtick.labelsize': size*0.75,
          'ytick.labelsize': size*0.75,
          'axes.titlepad': 25}
plt.rcParams.update(params)

Here is what I generally use in Jupyter Notebook:

# Jupyter Notebook settings

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
%autosave 0
%matplotlib inline
%load_ext autoreload
%autoreload 2

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"


# Imports for data analysis
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 2500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_colwidth', 2000)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)

#size=25
size=15
params = {'legend.fontsize': 'large',
          'figure.figsize': (20,8),
          'axes.labelsize': size,
          'axes.titlesize': size,
          'xtick.labelsize': size*0.75,
          'ytick.labelsize': size*0.75,
          'axes.titlepad': 25}
plt.rcParams.update(params)

回答 9

基于以上内容:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)

fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)

plot = fig.add_subplot(1, 1, 1)

plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)

for label in (plot.get_xticklabels() + plot.get_yticklabels()):
    label.set_fontproperties(font)

Based on the above stuff:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)

fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)

plot = fig.add_subplot(1, 1, 1)

plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)

for label in (plot.get_xticklabels() + plot.get_yticklabels()):
    label.set_fontproperties(font)

回答 10

这是Marius Retegan 答案的扩展。您可以对所有修改内容制作一个单独的JSON文件,然后通过rcParams.update加载它。所做的更改仅适用于当前脚本。所以

import json
from matplotlib import pyplot as plt, rcParams

s = json.load(open("example_file.json")
rcParams.update(s)

并将此“ example_file.json”保存在同一文件夹中。

{
  "lines.linewidth": 2.0,
  "axes.edgecolor": "#bcbcbc",
  "patch.linewidth": 0.5,
  "legend.fancybox": true,
  "axes.color_cycle": [
    "#348ABD",
    "#A60628",
    "#7A68A6",
    "#467821",
    "#CF4457",
    "#188487",
    "#E24A33"
  ],
  "axes.facecolor": "#eeeeee",
  "axes.labelsize": "large",
  "axes.grid": true,
  "patch.edgecolor": "#eeeeee",
  "axes.titlesize": "x-large",
  "svg.fonttype": "path",
  "examples.directory": ""
}

This is an extension to Marius Retegan answer. You can make a separate JSON file with all your modifications and than load it with rcParams.update. The changes will only apply to the current script. So

import json
from matplotlib import pyplot as plt, rcParams

s = json.load(open("example_file.json")
rcParams.update(s)

and save this ‘example_file.json’ in the same folder.

{
  "lines.linewidth": 2.0,
  "axes.edgecolor": "#bcbcbc",
  "patch.linewidth": 0.5,
  "legend.fancybox": true,
  "axes.color_cycle": [
    "#348ABD",
    "#A60628",
    "#7A68A6",
    "#467821",
    "#CF4457",
    "#188487",
    "#E24A33"
  ],
  "axes.facecolor": "#eeeeee",
  "axes.labelsize": "large",
  "axes.grid": true,
  "patch.edgecolor": "#eeeeee",
  "axes.titlesize": "x-large",
  "svg.fonttype": "path",
  "examples.directory": ""
}

回答 11

我完全同意Huster教授的观点,最简单的方法是更改​​图形的大小,从而可以保留默认字体。当将图形另存为pdf时,我只需要用bbox_inches选项对此进行补充,因为轴标签被切掉了。

import matplotlib.pyplot as plt
plt.figure(figsize=(4,3))
plt.savefig('Basic.pdf', bbox_inches='tight')

I totally agree with Prof Huster that the simplest way to proceed is to change the size of the figure, which allows keeping the default fonts. I just had to complement this with a bbox_inches option when saving the figure as a pdf because the axis labels were cut.

import matplotlib.pyplot as plt
plt.figure(figsize=(4,3))
plt.savefig('Basic.pdf', bbox_inches='tight')

如何在Matplotlib中设置图形标题和轴标签的字体大小?

问题:如何在Matplotlib中设置图形标题和轴标签的字体大小?

我正在Matplotlib中创建一个图形,如下所示:

from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

我想为图形标题和轴标签指定字体大小。我需要所有三个字体大小都不同,所以我不需要设置全局字体大小(mpl.rcParams['font.size']=x)。如何分别设置图形标题和轴标签的字体大小?

I am creating a figure in Matplotlib like this:

from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?


回答 0

对付像文本功能labeltitle等接受参数相同matplotlib.text.Text。对于字体大小,您可以使用size/fontsize

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

对于全局设置titlelabel大小,mpl.rcParams包含axes.titlesizeaxes.labelsize。(来自页面):

axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(据我所知,没有办法分别设置xy标记尺寸。)

而且我看到那axes.titlesize没有影响suptitle。我想,您需要手动设置。

Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):

axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(As far as I can see, there is no way to set x and y label sizes separately.)

And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.


回答 1

您也可以通过rcParams字典全局执行此操作:

import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)

You can also do this globally via a rcParams dictionary:

import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)

回答 2

如果您更习惯于使用ax对象进行绘图,则可能会ax.xaxis.label.set_size()更容易记住,或者至少在ipython终端中使用tab会更容易找到。看到效果后似乎需要重新绘制操作。例如:

import matplotlib.pyplot as plt

# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)

# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']

# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()

我不知道创建字幕后设置字幕大小的类似方法。

If you’re more used to using ax objects to do your plotting, you might find the ax.xaxis.label.set_size() easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:

import matplotlib.pyplot as plt

# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)

# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']

# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()

I don’t know of a similar way to set the suptitle size after it’s created.


回答 3

为了只修改标题的字体(而不是轴的字体),我使用了以下命令:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})

fontdict接受matplotlib.text.Text中的所有kwarg 。

To only modify the title’s font (and not the font of the axis) I used this:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})

The fontdict accepts all kwargs from matplotlib.text.Text.


回答 4

根据官方指南pylab不再建议使用。matplotlib.pyplot应该直接使用。

在全球范围内设置字体大小通过rcParams应该做

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16

# or

params = {'axes.labelsize': 16,
          'axes.titlesize': 16}
plt.rcParams.update(params)

# or

import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)

# or 

axes = {'labelsize': 16,
        'titlesize': 16}
mpl.rc('axes', **axes)

可以使用以下命令恢复默认值

plt.rcParams.update(plt.rcParamsDefault)

您还可以通过在matplotlib配置目录下的目录中创建样式表来完成此操作(您可以从中获取配置目录)。样式表格式为stylelibmatplotlib.get_configdir()

axes.labelsize: 16
axes.titlesize: 16

如果您有样式表,/path/to/mpl_configdir/stylelib/mystyle.mplstyle则可以通过

plt.style.use('mystyle')

# or, for a single section

with plt.style.context('mystyle'):
    # ...

您还可以创建(或修改)matplotlibrc文件共享格式

axes.labelsize = 16
axes.titlesize = 16

取决于您修改的matplotlibrc文件,这些更改将仅用于当前工作目录,具有matplotlibrc文件的所有工作目录,或具有matplotlibrc文件且没有其他matplotlibrc文件的所有工作目录。被指定。看到本节更多详细信息,定制matplotlib页面的。

rcParams可以通过找到完整的键列表plt.rcParams.keys(),但是要调整字体大小,请使用(此处引号为斜体)

  • axes.labelsizex和y标签的字体大小
  • axes.titlesize轴标题的字体大小
  • figure.titlesize图形标题的大小(Figure.suptitle()
  • xtick.labelsize刻度标签的字体大小
  • ytick.labelsize刻度标签的字体大小
  • legend.fontsize-图例的字体大小(plt.legend()fig.legend()
  • legend.title_fontsize-图例标题的字体大小,None设置为与默认轴相同。有关用法示例,请参见此答案

所有这些都接受字符串大小{'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'}floatin pt。字符串大小是相对于默认字体大小定义的,该默认大小由

  • font.size文本的默认字体大小,以pts为单位。标准值为10点

此外,可以通过以下方式指定重量(尽管仅用于默认值)

  • font.weight-所使用的字体的默认粗细text.Text。接受{100, 200, 300, 400, 500, 600, 700, 800, 900}'normal'(400),'bold'(700)'lighter',和'bolder'相对于当前重量)。

Per the official guide, use of pylab is no longer recommended. matplotlib.pyplot should be used directly instead.

Globally setting font sizes via rcParams should be done with

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16

# or

params = {'axes.labelsize': 16,
          'axes.titlesize': 16}
plt.rcParams.update(params)

# or

import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)

# or 

axes = {'labelsize': 16,
        'titlesize': 16}
mpl.rc('axes', **axes)

The defaults can be restored using

plt.rcParams.update(plt.rcParamsDefault)

You can also do this by creating a style sheet in the stylelib directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()). The style sheet format is

axes.labelsize: 16
axes.titlesize: 16

If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle then you can use it via

plt.style.use('mystyle')

# or, for a single section

with plt.style.context('mystyle'):
    # ...

You can also create (or modify) a matplotlibrc file which shares the format

axes.labelsize = 16
axes.titlesize = 16

Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.

A complete list of the rcParams keys can be retrieved via plt.rcParams.keys(), but for adjusting font sizes you have (italics quoted from here)

  • axes.labelsizeFontsize of the x and y labels
  • axes.titlesizeFontsize of the axes title
  • figure.titlesizeSize of the figure title (Figure.suptitle())
  • xtick.labelsizeFontsize of the tick labels
  • ytick.labelsizeFontsize of the tick labels
  • legend.fontsize – Fontsize for legends (plt.legend(), fig.legend())
  • legend.title_fontsize – Fontsize for legend titles, None sets to the same as the default axes. See this answer for usage example.

all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'} or a float in pt. The string sizes are defined relative to the default font size which is specified by

  • font.sizethe default font size for text, given in pts. 10 pt is the standard value

Additionally, the weight can be specified (though only for the default it appears) by

  • font.weight – The default weight of the font used by text.Text. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900} or 'normal' (400), 'bold' (700), 'lighter', and 'bolder' (relative with respect to current weight).

回答 5

更改字体大小的另一种方法是更改​​填充。当Python保存您的PNG时,您可以使用打开的对话框更改布局。轴之间的间距,如果需要,可以更改内边距。

An alternative solution to changing the font size is to change the padding. When Python saves your PNG, you can change the layout using the dialogue box that opens. The spacing between the axes, padding if you like can be altered at this stage.


回答 6

放在right_ax之前set_ylabel()

ax.right_ax.set_ylabel('AB scale')

Place right_ax before set_ylabel()

ax.right_ax.set_ylabel('AB scale')


回答 7

7(最佳解决方案)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6(较差的解决方案)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m

def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()

7 (best solution)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6 (slightly worse solution)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m

def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()

“%matplotlib内联”的目的

问题:“%matplotlib内联”的目的

有人可以向我解释到底有什么用%matplotlib inline吗?

Could someone explain to me what exactly is the use of %matplotlib inline?


回答 0

%matplotlib是IPython中的魔术函数。为了方便起见,我在这里引用相关文档供您阅读:

IPython有一组预定义的“魔术函数”,您可以使用命令行样式的语法来调用它们。有两种魔术,面向行的和面向单元的。换行符以%字符作为前缀,其工作方式与OS命令行调用非常相似:它们作为行的其余部分作为参数,其中的参数传递时不带括号或引号。线魔术可以返回结果,并且可以在作业的右侧使用。单元格魔术的前缀为%%,并且它们是函数,它们不仅作为该行的其余部分作为参数,而且还作为单独的参数作为其下方的行的参数。

%matplotlib inline 将matplotlib的后端设置为’inline’后端

使用此后端,绘图命令的输出将在Jupyter笔记本之类的前端内联显示,直接位于生成它的代码单元下方。然后,生成的图也将存储在笔记本文档中。

使用“内联”后端时,您的matplotlib图将包含在笔记本中代码旁边。还可能值得阅读如何内联制作IPython笔记本matplotlib绘图,以获取有关如何在代码中使用它的参考。

如果你想交互,以及,你可以使用nbagg后端%matplotlib notebook(在IPython中3.X),如所描述这里

%matplotlib is a magic function in IPython. I’ll quote the relevant documentation here for you to read for convenience:

IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Lines magics can return results and can be used in the right hand side of an assignment. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

%matplotlib inline sets the backend of matplotlib to the ‘inline’ backend:

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

When using the ‘inline’ backend, your matplotlib graphs will be included in your notebook, next to the code. It may be worth also reading How to make IPython notebook matplotlib plot inline for reference on how to use it in your code.

If you want interactivity as well, you can use the nbagg backend with %matplotlib notebook (in IPython 3.x), as described here.


回答 1

如果您正在运行IPython,它%matplotlib inline将使您的绘图输出出现并存储在笔记本中。

根据文件

要进行设置,matplotlib必须先执行%matplotlib magic command。这将执行必要的幕后设置,以使IPython能够与正确地并行工作matplotlib;但是,它实际上并不执行任何Python导入命令,也就是说,没有名称添加到命名空间。

由IPython提供的一个特别有趣的后端是 inline后端。此功能仅适用于Jupyter Notebook和Jupyter QtConsole。可以按以下方式调用它:

%matplotlib inline

使用此后端,绘图命令的输出将在Jupyter笔记本之类的前端内联显示,直接位于生成它的代码单元下方。然后,生成的图也将存储在笔记本文档中。

Provided you are running IPython, the %matplotlib inline will make your plot outputs appear and be stored within the notebook.

According to documentation

To set this up, before any plotting or import of matplotlib is performed you must execute the %matplotlib magic command. This performs the necessary behind-the-scenes setup for IPython to work correctly hand in hand with matplotlib; it does not, however, actually execute any Python import commands, that is, no names are added to the namespace.

A particularly interesting backend, provided by IPython, is the inline backend. This is available only for the Jupyter Notebook and the Jupyter QtConsole. It can be invoked as follows:

%matplotlib inline

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.


回答 2

如果要将绘图添加到Jupyter笔记本,则%matplotlib inline是标准解决方案。还有其他魔术命令将matplotlib在Jupyter中交互使用。

%matplotlibplt现在任何绘图命令都将导致图形窗口打开,并且可以运行其他命令来更新绘图。某些更改不会自动绘制,以强制更新,使用plt.draw()

%matplotlib notebook:将导致交互式绘图嵌入到笔记本中,您可以缩放图形并调整其大小

%matplotlib inline:仅在笔记本中绘制静态图像

If you want to add plots to your Jupyter notebook, then %matplotlib inline is a standard solution. And there are other magic commands will use matplotlib interactively within Jupyter.

%matplotlib: any plt plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()

%matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure

%matplotlib inline: only draw static images in the notebook


回答 3

从IPython 5.0和matplotlib 2.0开始,您可以避免使用IPython的特定魔术,而使用 matplotlib.pyplot.ion()/matplotlib.pyplot.ioff()具有在IPython之外工作的优点。

ipython文档

Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of IPython’s specific magic and use matplotlib.pyplot.ion()/matplotlib.pyplot.ioff() which have the advantages of working outside of IPython as well.

ipython docs


回答 4

如果您不知道后端是什么,可以阅读以下内容:https : //matplotlib.org/tutorials/introductory/usage.html#backends

有些人从python shell交互地使用matplotlib,并且在键入命令时弹出绘图窗口。有些人运行Jupyter笔记本并绘制内联图以进行快速数据分析。其他人则将matplotlib嵌入到wxpython或pygtk等图形用户界面中,以构建丰富的应用程序。有些人在批处理脚本中使用matplotlib从数值模拟生成后记图像,还有一些人运行Web应用程序服务器来动态提供图形。为了支持所有这些用例,matplotlib可以针对不同的输出,这些功能中的每一个都称为后端。“前端”是用户面对的代码,即绘图代码,而“后端”则是幕后的所有艰苦工作以制作图形。

因此,当您键入%matplotlib inline时,它将激活内联后端。如前几篇文章所述:

使用此后端,绘图命令的输出将在Jupyter笔记本之类的前端内联显示,直接位于生成它的代码单元下方。然后,生成的图也将存储在笔记本文档中。

If you don’t know what backend is , you can read this: https://matplotlib.org/tutorials/introductory/usage.html#backends

Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people run Jupyter notebooks and draw inline plots for quick data analysis. Others embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications. Some people use matplotlib in batch scripts to generate postscript images from numerical simulations, and still others run web application servers to dynamically serve up graphs. To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the “frontend” is the user facing code, i.e., the plotting code, whereas the “backend” does all the hard work behind-the-scenes to make the figure.

So when you type %matplotlib inline , it activates the inline backend. As discussed in the previous posts :

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.


回答 5

这只是意味着我们作为代码一部分创建的任何图形都将出现在同一笔记本中,而不是在单独的窗口中出现,如果我们不使用此魔术语句,则该窗口将发生。

It just means that any graph which we are creating as a part of our code will appear in the same notebook and not in separate window which would happen if we have not used this magic statement.


回答 6

解释清楚:

如果您不喜欢这样:

在此处输入图片说明

%matplotlib inline

在此处输入图片说明

然后在jupyter笔记本中保存它。

To explain it clear:

If you don’t like it like this:

enter image description here

add %matplotlib inline

enter image description here

and there you have it in your jupyter notebook.


回答 7

TL; DR

%matplotlib inline -显示输出内联


IPython内核具有通过执行代码来显示图的功能。IPython内核旨在与matplotlib绘图库无缝协作以提供此功能。

%matplotlib是一个魔术命令,它执行必要的幕后设置,以使IPython与IPython紧密配合matplotlib。它不执行任何Python导入命令,即没有名称添加到命名空间。

在单独的窗口中显示输出

%matplotlib

内联显示输出

(仅适用于Jupyter Notebook和Jupyter QtConsole)

%matplotlib inline

与交互式后端一起显示

(有效值'GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template'

%matplotlib gtk

示例-GTK3Agg-对GTK 3.x画布的Agg渲染(需要PyGObject和pycairo或cairocffi)。

有关matplotlib交互式后端的更多详细信息:此处


与开始IPython 5.0matplotlib 2.0你能避免使用IPython中的特殊魔法和使用matplotlib.pyplot.ion()/ matplotlib.pyplot.ioff() 其中有工作的IPython之外还有优势。

参考:IPython丰富的输出-交互式绘图

TL;DR

%matplotlib inline – Displays output inline


IPython kernel has the ability to display plots by executing code. The IPython kernel is designed to work seamlessly with the matplotlib plotting library to provide this functionality.

%matplotlib is a magic command which performs the necessary behind-the-scenes setup for IPython to work correctly hand-in-hand with matplotlib; it does not execute any Python import commands, that is, no names are added to the namespace.

Display output in separate window

%matplotlib

Display output inline

(available only for the Jupyter Notebook and the Jupyter QtConsole)

%matplotlib inline

Display with interactive backends

(valid values 'GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template')

%matplotlib gtk

Example – GTK3Agg – An Agg rendering to a GTK 3.x canvas (requires PyGObject and pycairo or cairocffi).

More details about matplotlib interactive backends: here


Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of IPython’s specific magic and use matplotlib.pyplot.ion()/matplotlib.pyplot.ioff() which have the advantages of working outside of IPython as well.

Refer: IPython Rich Output – Interactive Plotting


回答 8

如果您正在运行Jupyter Notebook,%matplotlib内联命令将使您的绘图输出出现在笔记本中,也可以存储。

Provided you are running Jupyter Notebook, the %matplotlib inline command will make your plot outputs appear in the notebook, also can be stored.


回答 9

不必写那个。没有(%matplotlib)魔术功能,对我来说效果很好。我正在使用Sypder编译器,这是Anaconda随附的。

It is not mandatory to write that. It worked fine for me without (%matplotlib) magic function. I am using Sypder compiler, one that comes with in Anaconda.


更改matplotlib中x或y轴上的“刻度频率”?

问题:更改matplotlib中x或y轴上的“刻度频率”?

我正在尝试修复python如何绘制我的数据。

x = [0,5,9,10,15]

y = [0,1,2,3,4]

然后我会做:

matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()

并且x轴的刻度线以5的间隔绘制。是否有办法使其显示1的间隔?

I am trying to fix how python plots my data.

Say

x = [0,5,9,10,15]

and

y = [0,1,2,3,4]

Then I would do:

matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()

and the x axis’ ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?


回答 0

您可以使用以下命令显式设置要在标记上打勾的位置plt.xticks

plt.xticks(np.arange(min(x), max(x)+1, 1.0))

例如,

import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()

(以防万一,np.arange使用它而不是Python的range函数min(x)max(x)它们是浮点数而不是整数。)


plt.plot(或ax.plot)功能将自动设置默认xy限制。如果您希望保留这些限制,而只是更改刻度线的步长,则可以使用ax.get_xlim()Matplotlib设置哪些限制。

start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))

默认的滴答格式器应将滴答值四舍五入为有意义的有效数字位数。但是,如果希望对格式有更多控制,则可以定义自己的格式器。例如,

ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))

这是一个可运行的示例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()

You could explicitly set where you want to tick marks with plt.xticks:

plt.xticks(np.arange(min(x), max(x)+1, 1.0))

For example,

import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()

(np.arange was used rather than Python’s range function just in case min(x) and max(x) are floats instead of ints.)


The plt.plot (or ax.plot) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set.

start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))

The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,

ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))

Here’s a runnable example:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()

回答 1

另一种方法是设置轴定位器:

import matplotlib.ticker as plticker

loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)

根据您的需要,有几种不同类型的定位器。

这是一个完整的示例:

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.show()

Another approach is to set the axis locator:

import matplotlib.ticker as plticker

loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)

There are several different types of locator depending upon your needs.

Here is a full example:

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.show()

回答 2

我喜欢这个解决方案(来自Matplotlib绘图食谱):

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]

tick_spacing = 1

fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()

该解决方案可以通过给给出的数字来明确控制刻度线间隔ticker.MultipleLocater(),允许自动确定极限,并且以后易于阅读。

I like this solution (from the Matplotlib Plotting Cookbook):

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]

tick_spacing = 1

fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()

This solution give you explicit control of the tick spacing via the number given to ticker.MultipleLocater(), allows automatic limit determination, and is easy to read later.


回答 3

如果有人对通用单线感兴趣,只需获取当前的报价,并通过对其他报价进行采样就可以使用它来设置新的报价。

ax.set_xticks(ax.get_xticks()[::2])

In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.

ax.set_xticks(ax.get_xticks()[::2])

回答 4

这有点棘手,但是到目前为止,我发现这样做是最干净/最容易理解的示例。这是从SO的答案中获得的:

隐藏matplotlib颜色栏中的每个第n个刻度标签的最干净方法?

for label in ax.get_xticklabels()[::2]:
    label.set_visible(False)

然后,您可以遍历标签,根据所需的密度将其设置为可见或不可见。

编辑:请注意,有时matplotlib会设置标签== '',因此看起来标签似乎不存在,而实际上却并不显示任何内容。为确保您遍历实际可见标签,可以尝试:

visible_labels = [lab for lab in ax.get_xticklabels() if lab.get_visible() is True and lab.get_text() != '']
plt.setp(visible_labels[::2], visible=False)

This is a bit hacky, but by far the cleanest/easiest to understand example that I’ve found to do this. It’s from an answer on SO here:

Cleanest way to hide every nth tick label in matplotlib colorbar?

for label in ax.get_xticklabels()[::2]:
    label.set_visible(False)

Then you can loop over the labels setting them to visible or not depending on the density you want.

edit: note that sometimes matplotlib sets labels == '', so it might look like a label is not present, when in fact it is and just isn’t displaying anything. To make sure you’re looping through actual visible labels, you could try:

visible_labels = [lab for lab in ax.get_xticklabels() if lab.get_visible() is True and lab.get_text() != '']
plt.setp(visible_labels[::2], visible=False)

回答 5

这是一个古老的话题,但是我时不时地碰到这个问题,并做了这个功能。这很方便:

import matplotlib.pyplot as pp
import numpy as np

def resadjust(ax, xres=None, yres=None):
    """
    Send in an axis and I fix the resolution as desired.
    """

    if xres:
        start, stop = ax.get_xlim()
        ticks = np.arange(start, stop + xres, xres)
        ax.set_xticks(ticks)
    if yres:
        start, stop = ax.get_ylim()
        ticks = np.arange(start, stop + yres, yres)
        ax.set_yticks(ticks)

像这样控制刻度线的一个警告是,添加一行之后,不再享受最大比例的交互式自动魔术更新。然后做

gca().set_ylim(top=new_top) # for example

并再次运行resadjust函数。

This is an old topic, but I stumble over this every now and then and made this function. It’s very convenient:

import matplotlib.pyplot as pp
import numpy as np

def resadjust(ax, xres=None, yres=None):
    """
    Send in an axis and I fix the resolution as desired.
    """

    if xres:
        start, stop = ax.get_xlim()
        ticks = np.arange(start, stop + xres, xres)
        ax.set_xticks(ticks)
    if yres:
        start, stop = ax.get_ylim()
        ticks = np.arange(start, stop + yres, yres)
        ax.set_yticks(ticks)

One caveat of controlling the ticks like this is that one does no longer enjoy the interactive automagic updating of max scale after an added line. Then do

gca().set_ylim(top=new_top) # for example

and run the resadjust function again.


回答 6

我开发了一个优雅的解决方案。考虑我们有X轴,还有X中每个点的标签列表。

例:
import matplotlib.pyplot as plt

x = [0,1,2,3,4,5]
y = [10,20,15,18,7,19]
xlabels = ['jan','feb','mar','apr','may','jun']
假设我只想显示“ feb”和“ jun”的刻度标签
xlabelsnew = []
for i in xlabels:
    if i not in ['feb','jun']:
        i = ' '
        xlabelsnew.append(i)
    else:
        xlabelsnew.append(i)
好,现在我们有一个虚假的标签列表。首先,我们绘制了原始版本。
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabels,rotation=45)
plt.show()
现在,修改版本。
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabelsnew,rotation=45)
plt.show()

I developed an inelegant solution. Consider that we have the X axis and also a list of labels for each point in X.

Example:
import matplotlib.pyplot as plt

x = [0,1,2,3,4,5]
y = [10,20,15,18,7,19]
xlabels = ['jan','feb','mar','apr','may','jun']
Let’s say that I want to show ticks labels only for ‘feb’ and ‘jun’
xlabelsnew = []
for i in xlabels:
    if i not in ['feb','jun']:
        i = ' '
        xlabelsnew.append(i)
    else:
        xlabelsnew.append(i)
Good, now we have a fake list of labels. First, we plotted the original version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabels,rotation=45)
plt.show()
Now, the modified version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabelsnew,rotation=45)
plt.show()

回答 7

如果您只想设置间距最小的简单衬板:

plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1))

对于较小的滴答声也很容易工作:

plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(1))

有点满口,但是很紧凑

if you just want to set the spacing a simple one liner with minimal boilerplate:

plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1))

also works easily for minor ticks:

plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(1))

a bit of a mouthfull, but pretty compact


回答 8

xmarks=[i for i in range(1,length+1,1)]

plt.xticks(xmarks)

这对我有用

如果您想在[1,5](包括1和5)之间打勾,请替换

length = 5
xmarks=[i for i in range(1,length+1,1)]

plt.xticks(xmarks)

This worked for me

if you want ticks between [1,5] (1 and 5 inclusive) then replace

length = 5

回答 9

纯Python实现

以下是所需功能的纯python实现,该功能可处理带有正,负或混合值的任何数字系列(int或float),并允许用户指定所需的步长:

import math

def computeTicks (x, step = 5):
    """
    Computes domain with given step encompassing series x
    @ params
    x    - Required - A list-like object of integers or floats
    step - Optional - Tick frequency
    """
    xMax, xMin = math.ceil(max(x)), math.floor(min(x))
    dMax, dMin = xMax + abs((xMax % step) - step) + (step if (xMax % step != 0) else 0), xMin - abs((xMin % step))
    return range(dMin, dMax, step)

样本输出

# Negative to Positive
series = [-2, 18, 24, 29, 43]
print(list(computeTicks(series)))

[-5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]

# Negative to 0
series = [-30, -14, -10, -9, -3, 0]
print(list(computeTicks(series)))

[-30, -25, -20, -15, -10, -5, 0]

# 0 to Positive
series = [19, 23, 24, 27]
print(list(computeTicks(series)))

[15, 20, 25, 30]

# Floats
series = [1.8, 12.0, 21.2]
print(list(computeTicks(series)))

[0, 5, 10, 15, 20, 25]

# Step – 100
series = [118.3, 293.2, 768.1]
print(list(computeTicks(series, step = 100)))

[100, 200, 300, 400, 500, 600, 700, 800]

样品用量

import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(computeTicks(x))
plt.show()

样本使用情况图

请注意,x轴具有均等以5间隔的整数值,而y轴具有不同的间隔(matplotlib默认行为,因为未指定刻度)。

Pure Python Implementation

Below’s a pure python implementation of the desired functionality that handles any numeric series (int or float) with positive, negative, or mixed values and allows for the user to specify the desired step size:

import math

def computeTicks (x, step = 5):
    """
    Computes domain with given step encompassing series x
    @ params
    x    - Required - A list-like object of integers or floats
    step - Optional - Tick frequency
    """
    xMax, xMin = math.ceil(max(x)), math.floor(min(x))
    dMax, dMin = xMax + abs((xMax % step) - step) + (step if (xMax % step != 0) else 0), xMin - abs((xMin % step))
    return range(dMin, dMax, step)

Sample Output

# Negative to Positive
series = [-2, 18, 24, 29, 43]
print(list(computeTicks(series)))

[-5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]

# Negative to 0
series = [-30, -14, -10, -9, -3, 0]
print(list(computeTicks(series)))

[-30, -25, -20, -15, -10, -5, 0]

# 0 to Positive
series = [19, 23, 24, 27]
print(list(computeTicks(series)))

[15, 20, 25, 30]

# Floats
series = [1.8, 12.0, 21.2]
print(list(computeTicks(series)))

[0, 5, 10, 15, 20, 25]

# Step – 100
series = [118.3, 293.2, 768.1]
print(list(computeTicks(series, step = 100)))

[100, 200, 300, 400, 500, 600, 700, 800]

Sample Usage

import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(computeTicks(x))
plt.show()

Plot of sample usage

Notice the x-axis has integer values all evenly spaced by 5, whereas the y-axis has a different interval (the matplotlib default behavior, because the ticks weren’t specified).


在Matplotlib中,该参数在fig.add_subplot(111)中意味着什么?

问题:在Matplotlib中,该参数在fig.add_subplot(111)中意味着什么?

有时我遇到这样的代码:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = plt.figure()
fig.add_subplot(111)
plt.scatter(x, y)
plt.show()

生成:

包含的代码生成的示例图

我一直在疯狂地阅读文档,但找不到关于的解释111。有时我看到一个212

论据fig.add_subplot()是什么意思?

Sometimes I come across code such as this:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = plt.figure()
fig.add_subplot(111)
plt.scatter(x, y)
plt.show()

Which produces:

Example plot produced by the included code

I’ve been reading the documentation like crazy but I can’t find an explanation for the 111. sometimes I see a 212.

What does the argument of fig.add_subplot() mean?


回答 0

这些是编码为单个整数的子图网格参数。例如,“ 111”表示“ 1×1网格,第一个子图”,而“ 234”表示“ 2×3网格,第4个子图”。

的替代形式add_subplot(111)add_subplot(1, 1, 1)

These are subplot grid parameters encoded as a single integer. For example, “111” means “1×1 grid, first subplot” and “234” means “2×3 grid, 4th subplot”.

Alternative form for add_subplot(111) is add_subplot(1, 1, 1).


回答 1

我认为最好用以下图片解释:

在此处输入图片说明

要初始化以上内容,请输入:

import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221)   #top left
fig.add_subplot(222)   #top right
fig.add_subplot(223)   #bottom left
fig.add_subplot(224)   #bottom right 
plt.show()

I think this would be best explained by the following picture:

enter image description here

To initialize the above, one would type:

import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221)   #top left
fig.add_subplot(222)   #top right
fig.add_subplot(223)   #bottom left
fig.add_subplot(224)   #bottom right 
plt.show()

回答 2

康斯坦丁的答案很明确,但对于更多背景,此行为是从Matlab继承的。

Matlab文档的“ 图形设置-每个图形显示多个图形”部分介绍了Matlab行为。

subplot(m,n,i)将图形窗口分成小子图的m×n矩阵,并为当前图选择ithe子图。地标沿着图形窗口的第一行编号,然后是第二行,依此类推。

The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.

The Matlab behavior is explained in the Figure Setup – Displaying Multiple Plots per Figure section of the Matlab documentation.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.


回答 3

我的解决方案是

fig = plt.figure()
fig.add_subplot(1, 2, 1)   #top and bottom left
fig.add_subplot(2, 2, 2)   #top right
fig.add_subplot(2, 2, 4)   #bottom right 
plt.show()

具有1和3合并的2x2网格

My solution is

fig = plt.figure()
fig.add_subplot(1, 2, 1)   #top and bottom left
fig.add_subplot(2, 2, 2)   #top right
fig.add_subplot(2, 2, 4)   #bottom right 
plt.show()

2x2 grid with 1 and 3 merge


回答 4

在此处输入图片说明

import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
plt.subplot(3,2,1)
plt.subplot(3,2,3)
plt.subplot(3,2,5)
plt.subplot(2,2,2)
plt.subplot(2,2,4)

第一个代码在具有3行2列的布局中创建第一个子图。

第一列中的三个图形表示3行。第二个图位于同一列中的第一个图的正下方,依此类推。

最后两个图的参数(2, 2)表示第二列只有两行,位置参数逐行移动。

enter image description here

import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
plt.subplot(3,2,1)
plt.subplot(3,2,3)
plt.subplot(3,2,5)
plt.subplot(2,2,2)
plt.subplot(2,2,4)

The first code creates the first subplot in a layout that has 3 rows and 2 columns.

The three graphs in the first column denote the 3 rows. The second plot comes just below the first plot in the same column and so on.

The last two plots have arguments (2, 2) denoting that the second column has only two rows, the position parameters move row wise.


回答 5

fig.add_subplot(ROW,COLUMN,POSITION)

  • ROW =行数
  • COLUMN =列数
  • POSITION =您要绘制的图形的位置

例子

`fig.add_subplot(111)` #There is only one subplot or graph  
`fig.add_subplot(211)`  *and*  `fig.add_subplot(212)` 

总共有2行1列,因此可以绘制2个子图。它的位置是第一。一共有2行,一列,因此可以绘制2个子图。其位置为第2个

fig.add_subplot(ROW,COLUMN,POSITION)

  • ROW=number of rows
  • COLUMN=number of columns
  • POSITION= position of the graph you are plotting

Examples

`fig.add_subplot(111)` #There is only one subplot or graph  
`fig.add_subplot(211)`  *and*  `fig.add_subplot(212)` 

There are total 2 rows,1 column therefore 2 subgraphs can be plotted. Its location is 1st. There are total 2 rows,1 column therefore 2 subgraphs can be plotted.Its location is 2nd


回答 6

add_subplot()方法有几个调用签名:

  1. add_subplot(nrows, ncols, index, **kwargs)
  2. add_subplot(pos, **kwargs)
  3. add_subplot(ax)
  4. add_subplot() <-自3.1.0起

通话1和2:

呼叫1和2实现彼此相同的功能(最大限制,如下所述)。可以将它们视为首先指定前两个数字(2×2、1×8、3×4等)的网格布局,例如:

f.add_subplot(3,4,1) 
# is equivalent to:
f.add_subplot(341)

两者都产生3行4列的(3 x 4 = 12)子图的子图排列。每次调用中的第三个数字表示要返回的轴对象,从左上方的1开始,向右增加

此代码说明了使用调用2的局限性:

#!/usr/bin/env python3
import matplotlib.pyplot as plt

def plot_and_text(axis, text):
  '''Simple function to add a straight line
  and text to an axis object'''
  axis.plot([0,1],[0,1])
  axis.text(0.02, 0.9, text)

f = plt.figure()
f2 = plt.figure()

_max = 12
for i in range(_max):
  axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
  plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))

  # If this check isn't in place, a 
  # ValueError: num must be 1 <= num <= 15, not 0 is raised
  if i < 9:
    axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
    plot_and_text(axis,chr(i+97) + ') ' + str(341+i))

f.tight_layout()
f2.tight_layout()
plt.show()

子图

您可以看到在LHS上调用1可以返回任何轴对象,但是在RHS上调用2只能返回到index = 9渲染子图j),k)和l)无法访问的状态。

即,它从文档中说明了这一点

pos是一个三位数的整数,其中第一位数是行数,第二位数是列数,第三位数是子图的索引。即fig.add_subplot(235)与fig.add_subplot(2、3、5)相同。请注意,所有整数必须小于10才能起作用


调用3

在极少数情况下,可以使用单个参数调用add_subplot,该子图坐标轴实例已在当前图形中创建,但未在图形的坐标轴列表中创建。


调用4(自3.1.0起):

如果未传递任何位置参数,则默认为(1,1,1)。

即,重现fig.add_subplot(111)问题中的呼叫。

The add_subplot() method has several call signatures:

  1. add_subplot(nrows, ncols, index, **kwargs)
  2. add_subplot(pos, **kwargs)
  3. add_subplot(ax)
  4. add_subplot() <– since 3.1.0

Calls 1 and 2:

Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2×2, 1×8, 3×4, etc), e.g:

f.add_subplot(3,4,1) 
# is equivalent to:
f.add_subplot(341)

Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.

This code illustrates the limitations of using call 2:

#!/usr/bin/env python3
import matplotlib.pyplot as plt

def plot_and_text(axis, text):
  '''Simple function to add a straight line
  and text to an axis object'''
  axis.plot([0,1],[0,1])
  axis.text(0.02, 0.9, text)

f = plt.figure()
f2 = plt.figure()

_max = 12
for i in range(_max):
  axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
  plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))

  # If this check isn't in place, a 
  # ValueError: num must be 1 <= num <= 15, not 0 is raised
  if i < 9:
    axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
    plot_and_text(axis,chr(i+97) + ') ' + str(341+i))

f.tight_layout()
f2.tight_layout()
plt.show()

subplots

You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.

I.e it illustrates this point from the documentation:

pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.


Call 3

In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure’s list of axes.


Call 4 (since 3.1.0):

If no positional arguments are passed, defaults to (1, 1, 1).

i.e., reproducing the call fig.add_subplot(111) in the question.