在python中画图时,怎么设置右边框也有和左边框相同的刻度?

2021-06-03 14:10发布

[图]就像这个图一样。

就像这个图一样。


4条回答

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号import pandas as pdimport numpy as np

新建隐藏坐标轴

from mpl_toolkits.axisartist.axislines import SubplotZeroimport 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')

这里写图片描述

from mpl_toolkits.axes_grid1 import host_subplotimport mpl_toolkits.axisartist as AAimport 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 = 100new_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()


这里写图片描述

# 第二坐标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()


这里写图片描述

刻度及标记

import mpl_toolkits.axisartist.axislines as axislines


fig = plt.figure(1, figsize=(10, 6))
fig.subplots_adjust(bottom=0.2)# 子图1ax1 = 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])# 子图2ax2 = 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")# 子图3ax3 = 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()


这里写图片描述

import matplotlib.ticker as ticker# Fixing random state for reproducibilitynp.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()


这里写图片描述

import mpl_toolkits.axisartist as axisartistdef 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()


这里写图片描述

共享坐标轴

# 共享坐标轴 方法一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轴  sharexax2 = plt.subplot(312, sharex=ax1)
plt.plot(t, s2)# make these tick labels invisibleplt.setp(ax2.get_xticklabels(), visible=False)
plt.title('我共享了X轴')# 共享X轴和Y轴   sharex、shareyax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
plt.plot(t, s3)
plt.xlim(0.01, 5.0)  #不起做用plt.title('我共享了X轴和Y轴')
plt.show()

这里写图片描述

# 共享坐标轴 方法二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')# 间距调整为0f.subplots_adjust(hspace=0)# 设置所有标签在外部for ax in axarr:
    ax.label_outer()

安之
3楼 · 2021-06-07 09:37

在设置label时,有语句plt.ylabel("标签内容",labelpad=20),这个labelpad就是标签与轴脊的距离,具体的我忘了,你可以按照这样的方式试一试。

灰机带翅膀
4楼 · 2021-08-20 16:20

image.png

matplotlib提供了双轴函数,可以实现双x轴或双y轴绘图。

帅帅马
5楼 · 2021-08-29 17:15

matplotlib提供了双轴函数,可以实现双x轴或双y轴绘图。

>>> import numpy as np>>> from matplotlib import pyplot as plt>>> x = np.linspace(1,10,100)>>> y1 = np.power(x, 4)>>> y2 = np.power(x, 3)>>> fig = plt.figure()>>> ax_left = fig.add_axes([0.1, 0.1, 0.8, 0.8])>>> ax_right = ax_left.twinx()>>> ax_left.semilogy(x, y1)[]>>> ax_right.semilogy(x, y2)[]>>> ax_right.set_ylim(1,10000)(1, 10000)>>> plt.show()


相关问题推荐

  • 回答 3

    换行。比如,print hello\nworld效果就是helloworld\n就是一个换行符。\是转义的意思,'\n'是换行,'\t'是tab,'\\'是,\ 是在编写程序中句子太长百,人为换行后加上\但print出来是一整行。...

  • 回答 42

    十种常见排序算法一般分为以下几种:(1)非线性时间比较类排序:a. 交换类排序(快速排序、冒泡排序)b. 插入类排序(简单插入排序、希尔排序)c. 选择类排序(简单选择排序、堆排序)d. 归并排序(二路归并排序、多路归并排序)(2)线性时间非比较类排序:...

  • 回答 70
    已采纳

    前景很好,中国正在产业升级,工业机器人和人工智能方面都会是强烈的热点,而且正好是在3~5年以后的时间。难度,肯定高,要求你有创新的思维能力,高数中的微积分、数列等等必须得非常好,软件编程(基础的应用最广泛的语言:C/C++)必须得很好,微电子(数字电...

  • 回答 28

    迭代器与生成器的区别:(1)生成器:生成器本质上就是一个函数,它记住了上一次返回时在函数体中的位置。对生成器函数的第二次(或第n次)调用,跳转到函数上一次挂起的位置。而且记录了程序执行的上下文。生成器不仅记住了它的数据状态,生成器还记住了程序...

  • 回答 9

    python中title( )属于python中字符串函数,返回’标题化‘的字符串,就是单词的开头为大写,其余为小写

  • 回答 6

    第一种解释:代码中的cnt是count的简称,一种电脑计算机内部的数学函数的名字,在Excel办公软件中计算参数列表中的数字项的个数;在数据库( sq| server或者access )中可以用来统计符合条件的数据条数。函数COUNT在计数时,将把数值型的数字计算进去;但是...

  • 回答 1

    head是方法,所以需要取小括号,即dataset.head()显示的则是前5行。data[:, :-1]和data[:, -1]。另外,如果想通过位置取数据,请使用iloc,即dataset.iloc[:, :-1]和dataset.iloc[:, -1],前者表示的是取所有行,但不包括最后一列的数据,结果是个DataFrame。...

  • Python入门简单吗2021-09-23 13:21
    回答 45

    挺简单的,其实课程内容没有我们想象的那么难、像我之前同学,完全零基础,培训了半年,直接出来就工作了,人家还在北京大公司上班,一个月15k,实力老厉害了

  • 回答 4

    Python针对众多的类型,提供了众多的内建函数来处理(内建是相对于导入import来说的,后面学习到包package时,将会介绍),这些内建函数功用在于其往往可对多种类型对象进行类似的操作,即多种类型对象的共有的操作;如果某种操作只对特殊的某一类对象可行,Pyt...

  • 回答 8

     相当于 ... 这里不是注释

  • 回答 4

    还有FIXME

  • 回答 3

    python的两个库:xlrd和xlutils。 xlrd打开excel,但是打开的excel并不能直接写入数据,需要用xlutils主要是复制一份出来,实现后续的写入功能。

  • 回答 8

    单行注释:Python中的单行注释一般是以#开头的,#右边的文字都会被当做解释说明的内容,不会被当做执行的程序。为了保证代码的可读性,一般会在#后面加一两个空格然后在编写解释内容。示例:#  单行注释print(hello world)注释可以放在代码上面也可以放在代...

  • 回答 2

    主要是按行读取,然后就是写出判断逻辑来勘测行是否为注视行,空行,编码行其他的:import linecachefile=open('3_2.txt','r')linecount=len(file.readlines())linecache.getline('3_2.txt',linecount)这样做的过程中发现一个问题,...

  • 回答 4

    或许是里面有没被注释的代码

  • 回答 26

    自学的话要看个人情况,可以先在B站找一下视频看一下

没有解决我的问题,去提问