matplotlib中沿曲线的注释

时间:2014-11-05 23:11:47

标签: python matplotlib

如何在matplotlib中的曲线上添加刻度注释?例如,假设我想生成此figure

我希望显示值(520,540,560,...)以及" ticks" (那些垂直于曲线的小线段)。有一个简单的方法吗? (假设我有一个3元组(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()

2 个答案:

答案 0 :(得分:1)

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

我将Axes的方面设置为"等于"否则很难绘制垂直于曲线的刻度线:

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

答案 1 :(得分:0)

看看matplotlib的这个模块。

这应该包含创建正确滴答所需的信息。

http://matplotlib.org/api/ticker_api.html

相关问题