我正在尝试使用matplotlib
在点附近带有空格的线条来实现图形,例如:
(来源:simplystatistics.org)
我知道set_dashes
函数,但它从起点设置周期性破折号,而不控制终点破折号。
编辑:我做了一个解决方法,但结果图只是一堆通常的线条,它不是一个对象。它还使用了另一个库pandas
,奇怪的是,它的工作方式并不完全符合我的预期——我想要相等的偏移量,但不知何故,它们显然与长度相关。
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
def my_plot(X,Y):
df = pd.DataFrame({
'x': X,
'y': Y,
})
roffset = 0.1
df['x_diff'] = df['x'].diff()
df['y_diff'] = df['y'].diff()
df['length'] = np.sqrt(df['x_diff']**2 + df['y_diff']**2)
aoffset = df['length'].mean()*roffset
# this is to drop values with negative magnitude
df['length_'] = df['length'][df['length']>2*aoffset]-2*aoffset
df['x_start'] = df['x'] -aoffset*(df['x_diff']/df['length'])
df['x_end'] = df['x']-df['x_diff']+aoffset*(df['x_diff']/df['length'])
df['y_start'] = df['y'] -aoffset*(df['y_diff']/df['length'])
df['y_end'] = df['y']-df['y_diff']+aoffset*(df['y_diff']/df['length'])
ax = plt.gca()
d = {}
idf = df.dropna().index
for i in idf:
line, = ax.plot(
[df['x_start'][i], df['x_end'][i]],
[df['y_start'][i], df['y_end'][i]],
linestyle='-', **d)
d['color'] = line.get_color()
ax.plot(df['x'], df['y'], marker='o', linestyle='', **d)
fig = plt.figure(figsize=(8,6))
axes = plt.subplot(111)
X = np.linspace(0,2*np.pi, 8)
Y = np.sin(X)
my_plot(X,Y)
plt.show()