python - matplotlib 中沿曲线的注释

标签 python matplotlib

如何在 matplotlib 中沿曲线添加刻度注释?例如,假设我想生成这个 figure .

我想显示值(520、540、560 等)以及“刻度线”(那些垂直于曲线的小线段)。有没有简单的方法可以做到这一点? (假设我有一个三元组列表(x,y,波长)作为手头的 np.ndarray。)

这里有一些示例代码和数据,可以下载 cc2012xyz2_5_5dp.csv 文件 here (从 http://www.cvrl.org 访问)。

import numpy as np
import matplotlib.pyplot as plt

with open("cc2012xyz2_5_5dp.csv", 'r') as f:
    lines = f.readlines()
horseshoe = np.array([[float(v) for v in l.strip().split(',')] for l in lines])
plt.plot(horseshoe[:,1], horseshoe[:,2])
for i in xrange(14, 47, 4):
    plt.annotate(str(horseshoe[i,0]), xy=horseshoe[i,1:3])
plt.show()

最佳答案

我认为您需要自己绘制所有刻度线,这是一个示例,代码量很大。

我将轴的纵横比设置为“相等”,否则很难绘制垂直于曲线的刻度:

import pandas as pd

df = pd.read_csv("cc2012xyz2_5_5dp.csv", header=None)
Labels = df[0].values
X0 = df[1].values
Y0 = df[2].values

ax = plt.gca()

plt.plot(X0, Y0)
ax.set_aspect("equal")

tick_len = 0.015
text_offset = 0.06

idx = np.arange(14, 47, 4)
x, y = X0[idx], Y0[idx]
xp, yp = X0[idx-1], Y0[idx-1]
xn, yn = X0[idx+1], Y0[idx+1]

labels = Labels[idx]
angle = np.arctan2(yn-yp, xn-xp) + np.pi / 2
x1, y1 = x + tick_len*np.cos(angle), y + tick_len*np.sin(angle)
x2, y2 = x + text_offset*np.cos(angle), y + text_offset*np.sin(angle)
from matplotlib.collections import LineCollection

tick_lines = LineCollection(np.c_[x, y, x1, y1].reshape(-1, 2, 2), color="k", lw=1)
ax.add_collection(tick_lines)
for i in range(len(idx)):
    plt.text(x2[i], y2[i], str(labels[i]), va="center", ha="center")

ax.set_xlim(-0.1, 0.8)
ax.set_ylim(0, 1.0)

输出:

enter image description here

关于python - matplotlib 中沿曲线的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26768934/

相关文章:

python - 子图的子图 Matplotlib/Seaborn

python - 尝试将类(在列表中)保存到文件中

python - SCons:如何在 scons 脚本中调用自定义的 python 函数并建立正确的依赖关系

Python:为什么动态添加的 __repr__ 方法不覆盖默认值

python - Matplotlib 中的 MonthLocator

python - 如何在Matplotlib中绘制二维结构化网格

python - matplotlib.pyplot 错误 "ImportError: cannot import name ' _path'"

python - Matplotlib - 动态绘图高度,水平条总是 1px 高度

python - 将brewer2mpl发散颜色图与matplotlib结合使用,gamma 给出的结果很差,其值不同于 1

python - 将不同的编码转换为ascii