Python 修改 x/y ticks ∈ Python 各种画图

主博客
Python 各种画图

Part.I 理论

导入画图的模块matplotlib.pyplot

import matplotlib.pyplot as plt			# 导入模块

Chap.I ax.tick_params 函数参数

ax.tick_params()函数可以对坐标轴进行一些控制,下面是它的参数的含义(实际上列下来也不太常看,用的时候直接复制粘贴即可)

Parameters
----------
axis : {'x', 'y', 'both'}, default: 'both'
    The axis to which the parameters are applied.
which : {'major', 'minor', 'both'}, default: 'major'
    The group of ticks to which the parameters are applied.
reset : bool, default: False
    Whether to reset the ticks to defaults before updating them.

Other Parameters
----------------
direction : {'in', 'out', 'inout'}
    Puts ticks inside the axes, outside the axes, or both.
length : float
    Tick length in points.
width : float
    Tick width in points.
color : color
    Tick color.
pad : float
    Distance in points between tick and label.
labelsize : float or str
    Tick label font size in points or as a string (e.g., 'large').
labelcolor : color
    Tick label color.
colors : color
    Tick color and label color.
zorder : float
    Tick and label zorder.
bottom, top, left, right : bool
    Whether to draw the respective ticks.
labelbottom, labeltop, labelleft, labelright : bool
    Whether to draw the respective tick labels.
labelrotation : float
    Tick label rotation
grid_color : color
    Gridline color.
grid_alpha : float
    Transparency of gridlines: 0 (transparent) to 1 (opaque).
grid_linewidth : float
    Width of gridlines in points.
grid_linestyle : str
    Any valid `.Line2D` line style spec.

常用的参数有

  • axis: 它可取的值有'x', 'y', 'both',默认是'both'。就是对谁发挥作用
  • colors: 颜色,默认是黑色
  • direction: 朝向,可取的值有'in', 'out', 'inout'
  • length, width: 小短线长度和宽度
  • pad: 小短线到文字的距离

Chap.II 常用语法

一般可以通过axis或者直接使用plt来修改ticks,下面是常用的操作(以xticks为例,yticks只需以y替换x即可)

ax.set_xticks(xticks)									# 设置xticks
ax.set_xticklabels(labels, rotation=-30, fontsize=15)	# 设置xticklab, 旋转角度 正逆时针,负顺时针
plt.xticks(ticks, labels, rotation=-30, fontsize=15)    # 上面两句合起来

实际上可用通过plt来获取axis

ax=plt.gca()

虽然可以通过fontsize来控制字体的大小,但是现在如果想改变字体的粗细和样式呢?可以进行如下的操作

x1_label = ax.get_xticklabels() 
[x1_label_temp.set_font(font3) for x1_label_temp in x1_label]

上面这两句话的意思就是:首先通过ax.get_xticklabels获取到xticklabels,然后通过set_font来改变字体的样式,其中font3是一个字典类型的字体样式。

另外,还可以通过ax.tick_params修改坐标轴刻度的朝向,下面是笔者常用的一句话。

ax.tick_params(axis='both', colors='black', direction='out', labelsize=15, width=1, length=1, pad=5)

杂记

# 控制 x ticklable 显示的位置(上方,默认是下方),都设为 false 表示不显示
ax.tick_params(top=True, labeltop=True, bottom=False, labelbottom=False)
# 控制 y ticklable 显示的位置(右边,默认是左边),都设为 false 表示不显示
ax.tick_params(right=True, labelright=True, left=False, labelleft=False)

Part.II 实操

下面举个例子

import matplotlib.pyplot as plt

font3 = {'weight': 400, 'size': 13, 'family':'Times New Roman'} # xlabes
x=list(range(5))
y=x
plt.scatter(x,y)
xticks=x
labels=['1st','2nd','3rd','4th','5th']
ax=plt.gca()
plt.xticks(xticks, labels, rotation=-30, fontsize=15)
x1_label = ax.get_xticklabels() 
[x1_label_temp.set_font(font3) for x1_label_temp in x1_label]
ax.tick_params(axis='both', colors='black', direction='out', labelsize=15, width=1, length=1, pad=5)
plt.show()

### 如何在 Python Matplotlib 中均分 Y 轴 在 Python 的 `Matplotlib` 库中,可以通过设置 `yticks` 方法来实现对 Y 轴的均匀划分。具体来说,可以定义一组等间距的数值作为 Y 轴刻度,并将其应用到图表上。 以下是具体的代码示例: ```python import matplotlib.pyplot as plt import numpy as np # 创建数据 x = np.linspace(0, 9, 10) y = np.sin(x) # 创建图像和坐标轴对象 fig, ax = plt.subplots() # 绘制折线图 ax.plot(x, y, marker='o') # 设置 Y 轴范围并均分 y_min, y_max = -1, 1 # 定义 Y 轴最小值和最大值 num_ticks = 5 # 刻度数量 yticks = np.linspace(y_min, y_max, num_ticks) # 计算等间距刻度值 ax.set_yticks(yticks) # 将计算好的刻度值应用于 Y 轴 # 添加标题和标签 ax.set_title("Y Axis with Uniform Ticks", fontsize=14) ax.set_xlabel("X-axis Label") ax.set_ylabel("Y-axis Label") plt.grid(True) # 显示网格以便更清晰观察 plt.show() ``` 上述代码通过调用 `np.linspace()` 函数生成一系列等间隔的数值[^1],并将这些数值传递给 `set_yticks()` 方法以完成 Y 轴的均匀划分操作。 #### 关键点说明 - 使用 `np.linspace(start, stop, num)` 可方便地创建指定数量的等差数列,其中 `start` 和 `stop` 是序列起始与终止值,而 `num` 表示希望得到的分割点数目。 - 对于自定义 Y 轴区间的情况,需先设定好上下限(即变量中的 `y_min`, `y_max`),再依据实际需求调整刻度密度(由参数 `num_ticks` 控制)[^3]。 ### 注意事项 如果原始数据分布不均衡或者存在极端异常值,则可能需要额外处理才能使最终呈现效果更加直观合理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流浪猪头拯救地球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值