绘制被数据中断的虚线(类似于等高线图)

Plot dashed line interrupted with data (similar to contour plot)

我遇到了一个(希望如此)简单的问题。 我的目标是绘制一条被数据(不仅是文本)打断的虚线。

因为我只发现通过 linestyle = 'dashed' 创建虚线,任何帮助将数据放在破折号之间表示感谢。

关于标签,Matplotlib 已经存在类似的东西 - 正如我在 the contour line demo.

中看到的

更新:

question link mentioned by Richard in comments 非常有帮助,但不是我在评论中提到的 100%。 目前,我是这样做的:

line_string2 = '-10 ' + u"\u00b0" +"C"
l, = ax1.plot(T_m10_X_Values,T_m10_Y_Values)
pos = [(T_m10_X_Values[-2]+T_m10_X_Values[-1])/2., (T_m10_Y_Values[-2]+T_m10_Y_Values[-1])/2.]
# transform data points to screen space
xscreen = ax1.transData.transform(zip(T_m10_Y_Values[-2::],T_m10_Y_Values[-2::]))
rot = np.rad2deg(np.arctan2(*np.abs(np.gradient(xscreen)[0][0][::-1])))
ltex = plt.text(pos[0], pos[1], line_string2, size=9, rotation=rot, color='b',ha="center", va="bottom",bbox = dict(ec='1',fc='1', alpha=0.5))

在这里您可以看到结果的快照。 -20°C是没有BBox的。

使用 annotate 的快速粗略回答:

import matplotlib.pyplot as plt
import numpy as np

x = list(reversed([1.81,1.715,1.78,1.613,1.629,1.714,1.62,1.738,1.495,1.669,1.57,1.877,1.385]))
y = [0.924,0.915,0.914,0.91,0.909,0.905,0.905,0.893,0.886,0.881,0.873,0.873,0.844]

def plot_with_text(x, y, text, text_count=None):
    text_count = (2 * (len(x) / len(text))) if text_count is None else text_count
    fig, ax = plt.subplots(1,1)
    l, = ax.plot(x,y)
    text_size = len(text) * 10
    idx_step = len(x) / text_count
    for idx_num in range(text_count):
        idx = int(idx_num * idx_step)
        text_pos = [x[idx], y[idx]]
        xscreen = ax.transData.transform(zip(x[max(0, idx-1):min(len(x), idx+2)], y[max(0, idx-1):min(len(y), idx+2)]))
        a = np.abs(np.gradient(xscreen)[0][0])
        rot = np.rad2deg(np.arctan2(*a)) - 90
        ax.annotate(text, xy=text_pos, color="r", bbox=dict(ec="1", fc="1", alpha=0.9), rotation=rot, ha="center", va="center")

plot_with_text(x, y, "test")

产量:

您可以调整偏移以获得更令人满意的结果。