【问题标题】:How to adjust the ticks and label size of a pandas plot with secondary_y如何使用 secondary_y 调整熊猫图的刻度和标签大小
【发布时间】:2021-11-27 09:19:02
【问题描述】:

我有一个使用pandas.DataFrame.plot 创建并指定secondary_y=True 的左右y 轴的图。

我想增加y轴刻度参数的字体大小,但似乎只有左侧y轴字体大小在增加。

import pandas as pd
import numpy as np

# sample dataframe
sample_length = range(1, 2+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])

# display(df.head(3))
         freq: 1x  freq: 2x
radians                    
0.00     0.000000  0.000000
0.01     0.010000  0.019999
0.02     0.019999  0.039989

# plot
ax1 = df.plot(y='freq: 1x', ylabel='left-Y', figsize=(8, 5))
df.plot(y='freq: 2x', secondary_y=True, ax=ax1)

ax1.tick_params(axis='both', labelsize=20)

增加右y轴字体大小的方法是什么?

【问题讨论】:

  • 你应该能够接受你自己的答案。

标签: python pandas matplotlib


【解决方案1】:
  • 使用ax2.set_ylabel('right-Y', fontsize=30) 访问secondary_y 轴,或使用.right_ax 属性从ax1 访问它。 dir(ax1) 将显示ax1 的所有可用方法。
    • 如果ax2.twinx() 一起实现,.right_ax 不起作用:
      • ax2 = ax1.twinx()df.plot(y='freq: 2x', ax=ax2)
      • ax2.set_ylabel('right-Y', fontsize=30).twinx() 一起使用
  • pandas User Guide: Plotting on a secondary y-axis
  • python 3.8.12pandas 1.3.4matplotlib 3.4.3 中测试
# plot the primary axes
ax1 = df.plot(y='freq: 1x', ylabel='left-Y', figsize=(8, 5))

# add the secondary y axes and assign it
ax2 = df.plot(y='freq: 2x', secondary_y=True, ax=ax1)

# adjust the ticks for the primary axes
ax1.tick_params(axis='both', labelsize=14)

# adjust the ticks for the secondary y axes
ax2.tick_params(axis='y', labelsize=25)

# set the primary (left) y label
ax1.set_ylabel('left Y', fontsize=18)

# set the secondary (right) y label from ax1
ax1.right_ax.set_ylabel('right-Y', fontsize=30)

# alternatively (only use one): set the secondary (right) y label from ax2
# ax2.set_ylabel('right-Y', fontsize=30)

plt.show()

注意

  • 如果绘制所有可用列,其中选择列应位于secondary_y,则无需指定y=secondary_y=['...', '...', ..., '...'] 可以是一个列表。
  • 因为副轴是和主轴同时创建的,所以副轴没有赋值给变量,但是可以通过ax2 = ax.right_ax来完成,然后ax2可以直接使用。
ax = df.plot(ylabel='left-Y', secondary_y=['freq: 2x'], figsize=(8, 5))

ax.tick_params(axis='both', labelsize=14)
ax.right_ax.tick_params(axis='y', labelsize=25)

ax.set_ylabel('left Y', fontsize=18)

# set the right y axes
ax.right_ax.set_ylabel('right-Y', fontsize=30)

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 2021-03-10
    • 2012-10-05
    • 2015-11-21
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多