精华内容
下载资源
问答
  • matplotlib隐藏坐标轴

    千次阅读 2019-10-18 15:33:54
    matplotlib隐藏坐标轴 matplotlib隐藏坐标轴: 1、方法一: # 隐藏坐标轴 pyplot.axes().get_xaxis().set_visible(False) pyplot.axes().get_yaxis().set_visible(False) 使用该方法会抛出警告,不影响使用: ...

    matplotlib隐藏坐标轴

    matplotlib隐藏坐标轴:

    1、方法一:

        # 隐藏坐标轴
        pyplot.axes().get_xaxis().set_visible(False)
        pyplot.axes().get_yaxis().set_visible(False)
    

    使用该方法会抛出警告,不影响使用:

     MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. 
     In a future version, a new instance will always be created and returned.  
     Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
      pyplot.axes().get_yaxis().set_visible(False)
    

    2、方法二:

        # 隐藏坐标轴
        pyplot.gca().get_xaxis().set_visible(False)
        pyplot.gca().get_yaxis().set_visible(False)
    
    展开全文
  • Python-matplotlib-隐藏坐标轴时出现的警告在《Python编程-从入门到实践》-【美】Eric Matthes 著,一书中第 301页,对于随机漫步5000点的项目,为了避免坐标轴干扰对随机漫步路径的注意,需要隐藏坐标轴。...

    Python-matplotlib-隐藏坐标轴时出现的警告

    在《Python编程-从入门到实践》-【美】Eric Matthes 著,一书中第 301页,对于随机漫步5000点的项目,为了避免坐标轴干扰对随机漫步路径的注意,需要隐藏坐标轴。

    环境:python3.9

    出现的问题

    import matplotlib.pyplot as plt

    from random_walk import RandomWalk

    while True:

    # Create an instance and draw

    rw = RandomWalk(50000)

    rw.fill_walk()

    # Hide axes

    plt.axes().get_xaxis().set_visible(False)

    plt.axes().get_yaxis().set_visible(False)

    point_numbers = list(range(rw.num_points))

    plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)

    # Highlight the start and end

    plt.scatter(0, 0, c='green', edgecolors='none', s=100)

    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)

    plt.show()

    keep_running = input("Make another walk?(y/n):")

    if keep_running == 'n':

    break

    在运行时出现的提示信息:

    D:\Python39\python.exe D:/Python39/matplotlib_work/rw_visual.py

    D:\Python39\matplotlib_work\rw_visual.py:16: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

    plt.axes().get_yaxis().set_visible(False)

    Make another walk?(y/n):

    这里是对隐藏坐标轴的两行代码的第二行进行了警告提示。如果将隐藏坐标轴的两行代码

    #--snip--

    # Hide axes

    plt.axes().get_xaxis().set_visible(False)

    plt.axes().get_yaxis().set_visible(False)

    #--snip--

    放置在

    #--snip--

    plt.show()

    #--snip--

    之后。则会出现两次同样的提示。

    问题分析

    根据对警告提示的说明。我们知道这个提示来自于matplotlib,其中提到了重复创建新实例的问题。那么我们只对一个实例进行操作,就能解决问题。

    问题的解决

    将代码:

    #--snip--

    # Hide axes

    plt.axes().get_xaxis().set_visible(False)

    plt.axes().get_yaxis().set_visible(False)

    #--snip--

    修改为:

    #--snip--

    # Hide axes

    current_axes = plt.axes()

    current_axes.xaxis.set_visible(False)

    current_axes.yaxis.set_visible(False)

    #--snip--

    这里我们将通过 plt.axes() 获得的实例存储在变量current_axes中,再通过对实例中属性xaxis和yaxis的修改来实现对坐标轴的隐藏。

    在我们可以在matplotlib/axex/_base.py中看到 xaxis 和 yaxis 。

    def _init_axis(self):

    # This is moved out of __init__ because non-separable axes don't use it

    self.xaxis = maxis.XAxis(self)

    self.spines['bottom'].register_axis(self.xaxis)

    self.spines['top'].register_axis(self.xaxis)

    self.yaxis = maxis.YAxis(self)

    self.spines['left'].register_axis(self.yaxis)

    self.spines['right'].register_axis(self.yaxis)

    self._update_transScale()

    再次运行就不会出现警告提示。

    展开全文
  • 学习https://matplotlib.org/gallery/index.html 记录,描述不一定准确,具体请参考官网 Matplotlib使用总结图 import matplotlib.pyplot as plt ...新建隐藏坐标轴 from mpl_toolkits.axisartist.
  • Matplotlib使用总结图import matplotlib.pyplot as pltplt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号import pandas as pdimport...

    Matplotlib使用总结图

    2019062811121832.png

    import matplotlib.pyplot as plt

    plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签

    plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号

    import pandas as pd

    import numpy as np

    新建隐藏坐标轴

    from mpl_toolkits.axisartist.axislines import SubplotZero

    import numpy as np

    fig = plt.figure(1, (10, 6))

    ax = SubplotZero(fig, 1, 1, 1)

    fig.add_subplot(ax)

    """新建坐标轴"""

    ax.axis["xzero"].set_visible(True)

    ax.axis["xzero"].label.set_text("新建y=0坐标")

    ax.axis["xzero"].label.set_color('green')

    # ax.axis['yzero'].set_visible(True)

    # ax.axis["yzero"].label.set_text("新建x=0坐标")

    # 新建一条y=2横坐标轴

    ax.axis["新建1"] = ax.new_floating_axis(nth_coord=0, value=2,axis_direction="bottom")

    ax.axis["新建1"].toggle(all=True)

    ax.axis["新建1"].label.set_text("y = 2横坐标")

    ax.axis["新建1"].label.set_color('blue')

    """坐标箭头"""

    ax.axis["xzero"].set_axisline_style("-|>")

    """隐藏坐标轴"""

    # 方法一:隐藏上边及右边

    # ax.axis["right"].set_visible(False)

    # ax.axis["top"].set_visible(False)

    #方法二:可以一起写

    ax.axis["top",'right'].set_visible(False)

    # 方法三:利用 for in

    # for n in ["bottom", "top", "right"]:

    # ax.axis[n].set_visible(False)

    """设置刻度"""

    ax.set_ylim(-3, 3)

    ax.set_yticks([-1,-0.5,0,0.5,1])

    ax.set_xlim([-5, 8])

    # ax.set_xticks([-5,5,1])

    #设置网格样式

    ax.grid(True, linestyle='-.')

    xx = np.arange(-4, 2*np.pi, 0.01)

    ax.plot(xx, np.sin(xx))

    # 于 offset 处新建一条纵坐标

    offset = (40, 0)

    new_axisline = ax.get_grid_helper().new_fixed_axis

    ax.axis["新建2"] = new_axisline(loc="right", offset=offset, axes=ax)

    ax.axis["新建2"].label.set_text("新建纵坐标")

    ax.axis["新建2"].label.set_color('red')

    plt.show()

    # 存为图像

    # fig.savefig('test.png')

    2019062811121833.png

    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 = 100

    new_fixed_axis = par2.get_grid_helper().new_fixed_axis

    par2.axis["right"] = new_fixed_axis(loc="right",

    axes=par2,

    offset=(offset, 0))

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

    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()

    host.axis["left"].label.set_color(p1.get_color())

    par1.axis["right"].label.set_color(p2.get_color())

    par2.axis["right"].label.set_color(p3.get_color())

    plt.draw()

    plt.show()

    2019062811121934.png

    # 第二坐标

    fig, ax_f = plt.subplots()

    # 这步是关键

    ax_c = ax_f.twinx()

    ax_d = ax_f.twiny()

    # automatically update ylim of ax2 when ylim of ax1 changes.

    # ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius)

    ax_f.plot(np.linspace(-40, 120, 100))

    ax_f.set_xlim(0, 100)

    # ax_f.set_title('第二坐标', size=14)

    ax_f.set_ylabel('Y轴',color='r')

    ax_f.set_xlabel('X轴',color='c')

    ax_c.set_ylabel('第二Y轴', color='b')

    ax_c.set_yticklabels(["$0$", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])

    # ax_c.set_ylim(1,5)

    ax_d.set_xlabel('第二X轴', color='g')

    ax_d.set_xlim(-1,1)

    plt.show()

    2019062811121935.png

    刻度及标记

    import mpl_toolkits.axisartist.axislines as axislines

    fig = plt.figure(1, figsize=(10, 6))

    fig.subplots_adjust(bottom=0.2)

    # 子图1

    ax1 = axislines.Subplot(fig, 131)

    fig.add_subplot(ax1)

    # for axis in ax.axis.values():

    # axis.major_ticks.set_tick_out(True) # 标签全部在外部

    ax1.axis[:].major_ticks.set_tick_out(True) # 这句和上面的for循环功能相同

    ax1.axis["left"].label.set_text("子图1 left标签") # 显示在左边

    # 设置刻度

    ax1.set_yticks([2,4,6,8])

    ax1.set_xticks([0.2,0.4,0.6,0.8])

    # 子图2

    ax2 = axislines.Subplot(fig, 132)

    fig.add_subplot(ax2)

    ax2.set_yticks([1,3,5,7])

    ax2.set_yticklabels(('one','two','three', 'four', 'five')) # 不显示‘five'

    ax2.set_xlim(5, 0) # X轴刻度

    ax2.axis["left"].set_axis_direction("right")

    ax2.axis["left"].label.set_text("子图2 left标签") # 显示在右边

    ax2.axis["bottom"].set_axis_direction("top")

    ax2.axis["right"].set_axis_direction("left")

    ax2.axis["top"].set_axis_direction("bottom")

    # 子图3

    ax3 = axislines.Subplot(fig, 133)

    fig.add_subplot(ax3)

    # 前两位表示X轴范围,后两位表示Y轴范围

    ax3.axis([40, 160, 0, 0.03])

    ax3.axis["left"].set_axis_direction("right")

    ax3.axis[:].major_ticks.set_tick_out(True)

    ax3.axis["left"].label.set_text("Long Label Left")

    ax3.axis["bottom"].label.set_text("Label Bottom")

    ax3.axis["right"].label.set_text("Long Label Right")

    ax3.axis["right"].label.set_visible(True)

    ax3.axis["left"].label.set_pad(0)

    ax3.axis["bottom"].label.set_pad(20)

    plt.show()

    2019062811121936.png

    import matplotlib.ticker as ticker

    # Fixing random state for reproducibility

    np.random.seed(19680801)

    fig, ax = plt.subplots()

    ax.plot(100*np.random.rand(20))

    # 设置 y坐标轴刻度

    formatter = ticker.FormatStrFormatter('$%1.2f')

    ax.yaxis.set_major_formatter(formatter)

    # 刻度

    for tick in ax.yaxis.get_major_ticks():

    tick.label1On = True # label1On 左边纵坐标

    tick.label2On = True # label2On 右边纵坐标

    tick.label1.set_color('red')

    tick.label2.set_color('green')

    # 刻度线

    for line in ax.yaxis.get_ticklines():

    # line is a Line2D instance

    line.set_color('green')

    line.set_markersize(25)

    line.set_markeredgewidth(3)

    # 刻度 文字

    for label in ax.xaxis.get_ticklabels():

    # label is a Text instance

    label.set_color('red')

    label.set_rotation(45)

    label.set_fontsize(16)

    plt.show()

    2019062811121937.png

    import mpl_toolkits.axisartist as axisartist

    def setup_axes(fig, rect):

    ax = axisartist.Subplot(fig, rect)

    fig.add_subplot(ax)

    ax.set_yticks([0.2, 0.8])

    # 设置刻度标记

    ax.set_yticklabels(["short", "loooong"])

    ax.set_xticks([0.2, 0.8])

    ax.set_xticklabels([r"$\frac{1}{2}\pi$", r"$\pi$"])

    return ax

    fig = plt.figure(1, figsize=(3, 5))

    fig.subplots_adjust(left=0.5, hspace=0.7)

    ax = setup_axes(fig, 311)

    ax.set_ylabel("ha=right")

    ax.set_xlabel("va=baseline")

    ax = setup_axes(fig, 312)

    # 刻度标签对齐方式

    ax.axis["left"].major_ticklabels.set_ha("center") # 居中

    ax.axis["bottom"].major_ticklabels.set_va("top") # 项部

    ax.set_ylabel("ha=center")

    ax.set_xlabel("va=top")

    ax = setup_axes(fig, 313)

    ax.axis["left"].major_ticklabels.set_ha("left") # 左边

    ax.axis["bottom"].major_ticklabels.set_va("bottom") # 底部

    ax.set_ylabel("ha=left")

    ax.set_xlabel("va=bottom")

    plt.show()

    2019062811121938.png

    共享坐标轴

    # 共享坐标轴 方法一

    t = np.arange(0.01, 5.0, 0.01)

    s1 = np.sin(2 * np.pi * t)

    s2 = np.exp(-t)

    s3 = np.sin(4 * np.pi * t)

    plt.subplots_adjust(top=2) #位置调整

    ax1 = plt.subplot(311)

    plt.plot(t, s1)

    plt.setp(ax1.get_xticklabels(), fontsize=6)

    plt.title('我是原坐标')

    # 只共享X轴 sharex

    ax2 = plt.subplot(312, sharex=ax1)

    plt.plot(t, s2)

    # make these tick labels invisible

    plt.setp(ax2.get_xticklabels(), visible=False)

    plt.title('我共享了X轴')

    # 共享X轴和Y轴 sharex、sharey

    ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)

    plt.plot(t, s3)

    plt.xlim(0.01, 5.0) #不起作用

    plt.title('我共享了X轴和Y轴')

    plt.show()

    2019062811121939.png

    # 共享坐标轴 方法二

    x = np.linspace(0, 2 * np.pi, 400)

    y = np.sin(x ** 2)

    f, axarr = plt.subplots(2, sharex=True)

    f.suptitle('共享X轴')

    axarr[0].plot(x, y)

    axarr[1].scatter(x, y, color='r')

    f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)

    f.suptitle('共享Y轴')

    ax1.plot(x, y)

    ax2.scatter(x, y)

    f, axarr = plt.subplots(3, sharex=True, sharey=True)

    f.suptitle('同时共享X轴和Y轴')

    axarr[0].plot(x, y)

    axarr[1].scatter(x, y)

    axarr[2].scatter(x, 2 * y ** 2 - 1, color='g')

    # 间距调整为0

    f.subplots_adjust(hspace=0)

    # 设置全部标签在外部

    for ax in axarr:

    ax.label_outer()

    2019062811121940.png

    2019062811121941.png

    2019062811121942.png

    放大缩小

    def f(t):

    return np.exp(-t) * np.cos(2*np.pi*t)

    t1 = np.arange(0.0, 3.0, 0.01)

    ax1 = plt.subplot(212)

    ax1.margins(0.05) # Default margin is 0.05, value 0 means fit

    ax1.plot(t1, f(t1), 'k')

    ax2 = plt.subplot(221)

    ax2.margins(2, 2) # Values >0.0 zoom out

    ax2.plot(t1, f(t1), 'r')

    ax2.set_title('Zoomed out')

    ax3 = plt.subplot(222)

    ax3.margins(x=0, y=-0.25) # Values in (-0.5, 0.0) zooms in to center

    ax3.plot(t1, f(t1), 'g')

    ax3.set_title('Zoomed in')

    plt.show()

    2019062811121943.png

    from matplotlib.transforms import Bbox, TransformedBbox, \

    blended_transform_factory

    from mpl_toolkits.axes_grid1.inset_locator import BboxPatch, BboxConnector,\

    BboxConnectorPatch

    def connect_bbox(bbox1, bbox2,

    loc1a, loc2a, loc1b, loc2b,

    prop_lines, prop_patches=None):

    if prop_patches is None:

    prop_patches = prop_lines.copy()

    prop_patches["alpha"] = prop_patches.get("alpha", 1) * 0.2

    c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines)

    c1.set_clip_on(False)

    c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines)

    c2.set_clip_on(False)

    bbox_patch1 = BboxPatch(bbox1, **prop_patches)

    bbox_patch2 = BboxPatch(bbox2, **prop_patches)

    p = BboxConnectorPatch(bbox1, bbox2,

    # loc1a=3, loc2a=2, loc1b=4, loc2b=1,

    loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,

    **prop_patches)

    p.set_clip_on(False)

    return c1, c2, bbox_patch1, bbox_patch2, p

    def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs):

    """

    ax1 : the main axes

    ax1 : the zoomed axes

    (xmin,xmax) : the limits of the colored area in both plot axes.

    connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will

    be marked. The keywords parameters will be used ti create

    patches.

    """

    trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)

    trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)

    bbox = Bbox.from_extents(xmin, 0, xmax, 1)

    mybbox1 = TransformedBbox(bbox, trans1)

    mybbox2 = TransformedBbox(bbox, trans2)

    prop_patches = kwargs.copy()

    prop_patches["ec"] = "none"

    prop_patches["alpha"] = 0.2

    c1, c2, bbox_patch1, bbox_patch2, p = \

    connect_bbox(mybbox1, mybbox2,

    loc1a=3, loc2a=2, loc1b=4, loc2b=1,

    prop_lines=kwargs, prop_patches=prop_patches)

    ax1.add_patch(bbox_patch1)

    ax2.add_patch(bbox_patch2)

    ax2.add_patch(c1)

    ax2.add_patch(c2)

    ax2.add_patch(p)

    return c1, c2, bbox_patch1, bbox_patch2, p

    def zoom_effect02(ax1, ax2, **kwargs):

    """

    ax1 : the main axes

    ax1 : the zoomed axes

    Similar to zoom_effect01. The xmin & xmax will be taken from the

    ax1.viewLim.

    """

    tt = ax1.transScale + (ax1.transLimits + ax2.transAxes)

    trans = blended_transform_factory(ax2.transData, tt)

    mybbox1 = ax1.bbox

    mybbox2 = TransformedBbox(ax1.viewLim, trans)

    prop_patches = kwargs.copy()

    prop_patches["ec"] = "none"

    prop_patches["alpha"] = 0.2

    c1, c2, bbox_patch1, bbox_patch2, p = \

    connect_bbox(mybbox1, mybbox2,

    loc1a=3, loc2a=2, loc1b=4, loc2b=1,

    prop_lines=kwargs, prop_patches=prop_patches)

    ax1.add_patch(bbox_patch1)

    ax2.add_patch(bbox_patch2)

    ax2.add_patch(c1)

    ax2.add_patch(c2)

    ax2.add_patch(p)

    return c1, c2, bbox_patch1, bbox_patch2, p

    import matplotlib.pyplot as plt

    plt.figure(1, figsize=(5, 5))

    ax1 = plt.subplot(221)

    ax2 = plt.subplot(212)

    ax2.set_xlim(0, 1)

    ax2.set_xlim(0, 5)

    zoom_effect01(ax1, ax2, 0.2, 0.8)

    ax1 = plt.subplot(222)

    ax1.set_xlim(2, 3)

    ax2.set_xlim(0, 5)

    zoom_effect02(ax1, ax2)

    plt.show()

    2019062811121944.png

    嵌入式标轴轴

    # 相同随机数

    np.random.seed(19680801)

    # create some data to use for the plot

    dt = 0.001

    t = np.arange(0.0, 10.0, dt)

    r = np.exp(-t[:1000] / 0.05) # impulse response

    x = np.random.randn(len(t))

    s = np.convolve(x, r)[:len(x)] * dt # colored noise

    # the main axes is subplot(111) by default

    plt.plot(t, s)

    #坐标轴

    plt.axis([0, 1, 1.1 * np.min(s), 2 * np.max(s)])

    plt.xlabel('time (s)')

    plt.ylabel('current (nA)')

    plt.title('Gaussian colored noise')

    # this is an inset axes over the main axes

    a = plt.axes([.65, .6, .2, .2], facecolor='k')

    n, bins, patches = plt.hist(s, 400, density=True, orientation='horizontal')

    plt.title('Probability')

    plt.xticks([])

    plt.yticks([])

    # # this is another inset axes over the main axes

    a = plt.axes([0.2, 0.6, .2, .2], facecolor='k')

    plt.plot(t[:len(r)], r)

    plt.title('Impulse response')

    plt.xlim(0, 0.2)

    plt.xticks([])

    plt.yticks([])

    plt.show()

    2019062811121945.png

    非常规坐标轴

    # 30 points between [0, 0.2) originally made using np.random.rand(30)*.2

    pts = np.array([

    0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018,

    0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075,

    0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008])

    # Now let's make two outlier points which are far away from everything.

    pts[[3, 14]] += .8

    # If we were to simply plot pts, we'd lose most of the interesting

    # details due to the outliers. So let's 'break' or 'cut-out' the y-axis

    # into two portions - use the top (ax) for the outliers, and the bottom

    # (ax2) for the details of the majority of our data

    f, (ax, ax2) = plt.subplots(2, 1, sharex=True)

    # plot the same data on both axes

    ax.plot(pts)

    ax2.plot(pts)

    # zoom-in / limit the view to different portions of the data

    ax.set_ylim(.78, 1.) # outliers only

    ax2.set_ylim(0, .22) # most of the data

    # hide the spines between ax and ax2

    ax.spines['bottom'].set_visible(False)

    ax2.spines['top'].set_visible(False)

    ax.xaxis.tick_top()

    ax.tick_params(labeltop=False) # don't put tick labels at the top

    ax2.xaxis.tick_bottom()

    # This looks pretty good, and was fairly painless, but you can get that

    # cut-out diagonal lines look with just a bit more work. The important

    # thing to know here is that in axes coordinates, which are always

    # between 0-1, spine endpoints are at these locations (0,0), (0,1),

    # (1,0), and (1,1). Thus, we just need to put the diagonals in the

    # appropriate corners of each of our axes, and so long as we use the

    # right transform and disable clipping.

    d = .015 # how big to make the diagonal lines in axes coordinates

    # arguments to pass to plot, just so we don't keep repeating them

    kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)

    ax.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal

    ax.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal

    kwargs.update(transform=ax2.transAxes) # switch to the bottom axes

    ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal

    ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal

    # What's cool about this is that now if we vary the distance between

    # ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(),

    # the diagonal lines will move accordingly, and stay right at the tips

    # of the spines they are 'breaking'

    plt.show()

    2019062811121946.png

    from matplotlib.transforms import Affine2D

    import mpl_toolkits.axisartist.floating_axes as floating_axes

    import numpy as np

    import mpl_toolkits.axisartist.angle_helper as angle_helper

    from matplotlib.projections import PolarAxes

    from mpl_toolkits.axisartist.grid_finder import (FixedLocator, MaxNLocator,

    DictFormatter)

    import matplotlib.pyplot as plt

    # Fixing random state for reproducibility

    np.random.seed(19680801)

    def setup_axes1(fig, rect):

    """

    A simple one.

    """

    tr = Affine2D().scale(2, 1).rotate_deg(30)

    grid_helper = floating_axes.GridHelperCurveLinear(

    tr, extremes=(-0.5, 3.5, 0, 4))

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)

    fig.add_subplot(ax1)

    aux_ax = ax1.get_aux_axes(tr)

    grid_helper.grid_finder.grid_locator1._nbins = 4

    grid_helper.grid_finder.grid_locator2._nbins = 4

    return ax1, aux_ax

    def setup_axes2(fig, rect):

    """

    With custom locator and formatter.

    Note that the extreme values are swapped.

    """

    tr = PolarAxes.PolarTransform()

    pi = np.pi

    angle_ticks = [(0, r"$0$"),

    (.25*pi, r"$\frac{1}{4}\pi$"),

    (.5*pi, r"$\frac{1}{2}\pi$")]

    grid_locator1 = FixedLocator([v for v, s in angle_ticks])

    tick_formatter1 = DictFormatter(dict(angle_ticks))

    grid_locator2 = MaxNLocator(2)

    grid_helper = floating_axes.GridHelperCurveLinear(

    tr, extremes=(.5*pi, 0, 2, 1),

    grid_locator1=grid_locator1,

    grid_locator2=grid_locator2,

    tick_formatter1=tick_formatter1,

    tick_formatter2=None)

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)

    fig.add_subplot(ax1)

    # create a parasite axes whose transData in RA, cz

    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax

    ax1.patch.zorder = 0.9 # but this has a side effect that the patch is

    # drawn twice, and possibly over some other

    # artists. So, we decrease the zorder a bit to

    # prevent this.

    return ax1, aux_ax

    def setup_axes3(fig, rect):

    """

    Sometimes, things like axis_direction need to be adjusted.

    """

    # rotate a bit for better orientation

    tr_rotate = Affine2D().translate(-95, 0)

    # scale degree to radians

    tr_scale = Affine2D().scale(np.pi/180., 1.)

    tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()

    grid_locator1 = angle_helper.LocatorHMS(4)

    tick_formatter1 = angle_helper.FormatterHMS()

    grid_locator2 = MaxNLocator(3)

    # Specify theta limits in degrees

    ra0, ra1 = 8.*15, 14.*15

    # Specify radial limits

    cz0, cz1 = 0, 14000

    grid_helper = floating_axes.GridHelperCurveLinear(

    tr, extremes=(ra0, ra1, cz0, cz1),

    grid_locator1=grid_locator1,

    grid_locator2=grid_locator2,

    tick_formatter1=tick_formatter1,

    tick_formatter2=None)

    ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)

    fig.add_subplot(ax1)

    # adjust axis

    ax1.axis["left"].set_axis_direction("bottom")

    ax1.axis["right"].set_axis_direction("top")

    ax1.axis["bottom"].set_visible(False)

    ax1.axis["top"].set_axis_direction("bottom")

    ax1.axis["top"].toggle(ticklabels=True, label=True)

    ax1.axis["top"].major_ticklabels.set_axis_direction("top")

    ax1.axis["top"].label.set_axis_direction("top")

    ax1.axis["left"].label.set_text(r"cz [km$^{-1}$]")

    ax1.axis["top"].label.set_text(r"$\alpha_{1950}$")

    # create a parasite axes whose transData in RA, cz

    aux_ax = ax1.get_aux_axes(tr)

    aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax

    ax1.patch.zorder = 0.9 # but this has a side effect that the patch is

    # drawn twice, and possibly over some other

    # artists. So, we decrease the zorder a bit to

    # prevent this.

    return ax1, aux_ax

    fig = plt.figure(1, figsize=(8, 4))

    fig.subplots_adjust(wspace=0.3, left=0.05, right=0.95)

    ax1, aux_ax1 = setup_axes1(fig, 131)

    aux_ax1.bar([0, 1, 2, 3], [3, 2, 1, 3])

    ax2, aux_ax2 = setup_axes2(fig, 132)

    theta = np.random.rand(10)*.5*np.pi

    radius = np.random.rand(10) + 1.

    aux_ax2.scatter(theta, radius)

    ax3, aux_ax3 = setup_axes3(fig, 133)

    theta = (8 + np.random.rand(10)*(14 - 8))*15. # in degrees

    radius = np.random.rand(10)*14000.

    aux_ax3.scatter(theta, radius)

    plt.show()

    2019062811121947.png

    import numpy as np

    import matplotlib.pyplot as plt

    import mpl_toolkits.axisartist.angle_helper as angle_helper

    from matplotlib.projections import PolarAxes

    from matplotlib.transforms import Affine2D

    from mpl_toolkits.axisartist import SubplotHost

    from mpl_toolkits.axisartist import GridHelperCurveLinear

    def curvelinear_test2(fig):

    """Polar projection, but in a rectangular box.

    """

    # see demo_curvelinear_grid.py for details

    tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform()

    extreme_finder = angle_helper.ExtremeFinderCycle(20,

    20,

    lon_cycle=360,

    lat_cycle=None,

    lon_minmax=None,

    lat_minmax=(0,

    np.inf),

    )

    grid_locator1 = angle_helper.LocatorDMS(12)

    tick_formatter1 = angle_helper.FormatterDMS()

    grid_helper = GridHelperCurveLinear(tr,

    extreme_finder=extreme_finder,

    grid_locator1=grid_locator1,

    tick_formatter1=tick_formatter1

    )

    ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)

    fig.add_subplot(ax1)

    # Now creates floating axis

    # floating axis whose first coordinate (theta) is fixed at 60

    ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)

    axis.label.set_text(r"$\theta = 60^{\circ}$")

    axis.label.set_visible(True)

    # floating axis whose second coordinate (r) is fixed at 6

    ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)

    axis.label.set_text(r"$r = 6$")

    ax1.set_aspect(1.)

    ax1.set_xlim(-5, 12)

    ax1.set_ylim(-5, 10)

    ax1.grid(True)

    fig = plt.figure(1, figsize=(5, 5))

    fig.clf()

    curvelinear_test2(fig)

    plt.show()

    2019062811121948.png

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    展开全文
  • 入门matplotlib坐标轴

    2021-02-05 19:24:22
    的颜色及隐藏轴边框 import pandas as pd import matplotlib.pyplot as plt # 遇到数据中有中文的时候,一定要先设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文 x,y = plt.subplots...

    轴的颜色及隐藏轴边框

    import pandas as pd
    import matplotlib.pyplot as plt
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    x,y = plt.subplots(1,1)
    y.spines['left'].set_color('r')
    y.spines['bottom'].set_color('b')
    y.spines['top'].set_color('None')
    y.spines['right'].set_color('None')
    plt.show()
    

    在这里插入图片描述

    翻转x轴和y轴(坐标轴从大到小)

    import pandas as pd
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    x,y = plt.subplots(1,1)
    y.spines['left'].set_color('r')
    y.spines['bottom'].set_color('b')
    y.spines['top'].set_color('None')
    y.spines['right'].set_color('None')
    plt.gca().invert_xaxis()  #先取值 翻转y到右边
    plt.gca().invert_yaxis()
    plt.show()
    

    在这里插入图片描述

    隐藏x与y轴

    import pandas as pd
    import matplotlib.pyplot as plt
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    x,y = plt.subplots(1,1)
    y.spines['left'].set_color('None')
    y.spines['bottom'].set_color('None')
    y.spines['top'].set_color('None')
    y.spines['right'].set_color('None')
    plt.xticks([])   #隐藏刻度标签
    plt.yticks([])   #隐藏刻度标签
    plt.show()
    
    import pandas as pd
    import matplotlib.pyplot as plt
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    x,y = plt.subplots(1,1)
    y.spines['left'].set_color('None')
    y.spines['bottom'].set_color('None')
    y.spines['top'].set_color('r')   #颜色也要调换
    y.spines['right'].set_color('b')  
    y.xaxis.set_ticks_position('top') # x轴显示在顶部
    y.yaxis.set_ticks_position('right')   # y轴显示在顶部
    plt.show()
    

    在这里插入图片描述

    突出某个坐标值

    import pandas as pd
    import matplotlib.pyplot as plt
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    path = 'C:/Users/Administrator/Desktop/playground2/17.直方图.xlsx'
    data = pd.read_excel(path)
    
    x,y = plt.subplots(1,1)
    y.plot(data.序号,data.身高)
    plt.gca().get_xticklabels()[2].set(color='r',fontsize=30)  #先取坐标 再改格式
    plt.show()
    

    在这里插入图片描述

    坐标轴刻度的调整

    将x轴 y轴分成均等的部分

    import pandas as pd
    import matplotlib.pyplot as plt
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    path = 'C:/Users/Administrator/Desktop/playground2/17.直方图.xlsx'
    data = pd.read_excel(path)
    x,y = plt.subplots(1,1)
    y.plot(data.序号,data.身高)
    plt.gca().locator_params("x",nbins=5)   #x轴被分成5份 x,y 都分成5份的话直接省略x
    plt.show()
    

    将x轴 y轴分成7的倍数

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.pyplot as ticker
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    path = 'C:/Users/Administrator/Desktop/playground2/17.直方图.xlsx'
    data = pd.read_excel(path)
    x,y = plt.subplots(1,1)
    y.plot(data.序号,data.身高)
    plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(7))  #x轴设置成7的倍数
    plt.show()
    

    在这里插入图片描述
    x轴,y轴保留小数位

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.pyplot as ticker
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    path = 'C:/Users/Administrator/Desktop/playground2/17.直方图.xlsx'
    data = pd.read_excel(path)
    x,y = plt.subplots(1,1)
    y.plot(data.序号,data.身高)
    plt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%.1f%%'))  #1是指保留一位小数
    plt.show()
    

    在这里插入图片描述

    第二种处理日期轴的方法

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    path = 'C:/Users/Administrator/Desktop/playground2/12.日期.xlsx'
    data = pd.read_excel(path)
    x,y = plt.subplots(1,1)
    y.plot(data.日期,data.销售)
    plt.gca().xaxis.set_major_formatter(mpl.dates.DateFormatter("%Y-%m"))
    plt.show()
    

    在这里插入图片描述

    x轴与y轴区间

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    # 遇到数据中有中文的时候,一定要先设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
    path = 'C:/Users/Administrator/Desktop/playground2/08.折线图.xlsx'
    data = pd.read_excel(path)
    x,y = plt.subplots(1,1)
    y.plot(data.时间,data.蔬菜)=plt.gca()
    # 轴.set_xlim([0, 10]) #设置X轴的区间
    # 轴.set_ylim([0, 100]) #Y轴区间
    # 轴.axis([0, 10, 0, 100]) #X、Y轴区间 [xmin,xmax,ymin,ymax].set_ylim(bottom=-10) #Y轴下限.set_xlim(right=25) #X轴上限
    plt.show()
    

    在这里插入图片描述

    展开全文
  • fig = plt.figure() ax = fig.add_subplot(111) ...# 隐藏 上边 和 右边 的坐标轴 ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') # 移动 x 轴 和 y轴 到 原点位置 ax...
  • Python-matplotlib-隐藏坐标轴时图片没有数据显示 在《Python编程-从入门到实践》-【美】Eric Matthes 著,一书中对于随机漫步5000点的项目,为了避免坐标轴干扰对随机漫步路径的注意,需要隐藏坐标轴。 根据代码...
  • 目录Python-matplotlib-隐藏坐标轴时出现的警告出现的问题问题分析问题的解决 Python-matplotlib-隐藏坐标轴时出现的警告 在《Python编程-从入门到实践》-【美】Eric Matthes 著,一书中第 301页,对于随机漫步5000...
  • from random import choice import matplotlib.pyplot as plt x_start = [0] y_start = [0] #生成坐标矩阵 while len(x_start)<10000: x_direction=choice([-1,1]) x_distance=choice([0,1,2,3,4]) x_s...
  • 前面学习过隐藏坐标轴的方式来实现三Y轴的显示,并没有移动过坐标轴的位置,但是有时候需要移动坐标到某些位置,这样看曲线更加方便,比如像下图: 这时看到抛物线曲线分布在Y轴的两边,Y轴就是一条对称轴,分析...
  • matplotlib用断裂的坐标轴表示无穷

    千次阅读 2016-08-30 18:58:40
    最近作图需要用断裂的坐标轴表示无穷点,正好想抛弃pyplot,转向面向对象的matplotlib绘图,所以尝试了用面向对象的方法绘制这个图: 关键在于右边两个斜杠断裂坐标轴,它的做法是把两个图拼在一起,问题包括怎么...
  • matplotlib中,边框线的设置与坐标轴,子图的边界息息相关。下面我们通过axes的API来设置边框线。 边框线及坐标轴的设置1.边框线的设置1.1 边框线隐藏1.2 边框线线宽、线型、颜色2.坐标轴的设置2.1 隐藏坐标刻度及...
  • 4.Matplotlib多子图,文字和注释以及自定义坐标轴

    千次阅读 多人点赞 2020-08-08 14:01:57
    文章目录Matplotlib绘制多子图,文字和注释以及自定义坐标轴刻度多子图自定义子图位置网格多子图plt.subplot() / add_subplot方法循环创建plt.subplots()直接创建plt.GridSpec()创建不同形状多子图不同形状子图表示...
  • 不显示右侧和顶端的坐标轴是通过...# 隐藏右侧和顶端的坐标轴 ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) 可以参照matplotlib官方文档之Ticks and spines下边的例子进行操作。 ...
  • matplotlib绘图改变边框粗细颜色、小数点后几位显示、网格粗细 1、原图 import numpy as np import matplotlib.pyplot as plt y = np.arange(1,10,1) x = np.arange(1,10,1) plt.plot(x,y) 2、网格设置...
  • Matplotlib

    2020-02-27 20:20:18
    坐标轴网格坐标范围坐标刻度数学刻度坐标背景色坐标轴隐藏坐标轴移动多坐标轴二、各种图1. 散点图DataFrameSeries2. 条形图DataFrameSeries3. 直方图DataFrame4. 箱线图DataFrame5. 面积图DataFrame6. 饼状图...

空空如也

空空如也

1 2 3
收藏数 49
精华内容 19
关键字:

matplotlib隐藏坐标轴