matplotlib: ylabel on the right

本文介绍如何使用Python的pylab库在绘图中设置右侧的标签,包括坐标轴的位置调整、文字旋转及对齐方式等。通过示例代码展示了如何实现这一功能,并解决了文字超出坐标轴范围被裁剪的问题。
To make a ylabel on the right, use the text command. You need to set
the transform to use axes coordinates (ax.transAxes), rotate the text
vertically, make the horizontal alignment left, the vertical alignment
centered. Note that x, y = 1, 0.5 is the right, middle of the axes in
axes coordinates. You also need to turn off clipping, so the text can
appear outside the axes w/o being clipped by the axes bounding box,
which is the default behavior.

from pylab import *

plot([1,2,3])

text(1.02, 0.5, 'volts',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=gca().transAxes,
clip_on=False)
show()

转载于:https://www.cnblogs.com/bioinfo/archive/2009/04/23/1441797.html

### Matplotlib 练习题、教程与实例 #### 导入必要的库 为了使用 `Matplotlib` 创建图形,通常会先导入该库以及辅助计算的 NumPy 库: ```python import matplotlib.pyplot as plt import numpy as np ``` #### 基本绘图操作 创建简单的折线图可以通过定义数据集并调用 `plt.plot()` 方法来实现。下面的例子展示了如何绘制一个简单的一次函数图像,并设置了坐标轴范围和标签[^2]。 ```python x = np.arange(10) y = 2 * x + 5 plt.plot(x, y, "o") plt.xlim(1, 10) plt.ylim(5, 25) plt.xticks(range(1, 11)) plt.yticks([5, 10, 15, 20, 25]) plt.xlabel("X 轴说明") plt.ylabel("Y 轴说明") plt.title("Matplotlib 示例") plt.show() ``` #### 使用 Plot 方法绘制正弦波形 除了直线外,还可以通过 NumPy 提供的三角函数轻松生成周期性的信号波形,比如正弦波。这里展示了一个在区间 `[0, 10]` 上绘制正弦曲线的方法[^3]。 ```python x_values = np.linspace(0, 10, num=100) sin_values = np.sin(x_values) plt.figure(figsize=(8, 4)) plt.plot(x_values, sin_values, label="Sine Wave", color="blue") plt.axhline(y=0, linestyle="--", color="#d3d3d3") # 添加水平虚线作为参考 plt.grid(True, which='both', alpha=.3) # 显示网格线 plt.legend(loc="best") plt.title("Sinusoidal Function Visualization") plt.show() ``` #### 数据分析中的应用案例 当处理实际的数据集时,可以结合 Pandas 和 Seaborn 来增强可视化效果。这段代码读取 CSV 文件后进行了预处理,并最终呈现了一张关于经济指标之间关系的散点图及其拟合趋势线[^4]。 ```python import pandas as pd from matplotlib import rcParams rcParams['axes.unicode_minus'] = False # 解决中文显示问题 rcParams['font.family'] = 'SimHei' economic_data = pd.read_csv('path_to_your_file.csv') transformed_economic_data = np.log(economic_data[['cpi', 'm1', 'tbilrate', 'unemp']]).diff().dropna() sns.regplot( x='m1', y='unemp', data=transformed_economic_data, scatter_kws={"color": "#ff7f0e"}, line_kws={"color": "#1f77b4"} ) plt.xlabel('货币供应量 (M1)') plt.ylabel('失业率 (%)') plt.title('对数变化后的 M1 对 失业率的影响') plt.tight_layout() plt.show() ``` #### 展示多条时间序列数据 对于具有多个特征的时间序列数据集来说,在同一图表上比较不同维度的变化情况是非常有用的。此片段演示了怎样在同一窗口内分别以红色实线表示 HP 列前十五项数值,绿色虚线代表 Attack 列相应位置上的值[^5]。 ```python df_example = pd.DataFrame({ 'HP': range(1, 16), 'Attack': list(reversed(range(1, 16))) }) fig, ax = plt.subplots() ax.plot(df_example.index, df_example['HP'], '-r', linewidth=2, markersize=8, label='HP') ax.plot(df_example.index, df_example['Attack'], ':g', marker='s', markersize=6, label='Attack') ax.set_xlabel('Index') ax.set_ylabel('Values') ax.set_title('Comparison Between HP and Attack Over Time') ax.legend(frameon=True, loc='upper right') plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值