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

时间:2015-07-30 10:00:59

标签: python matplotlib plot line contour

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

Example of how I would imagine a possible result

由于我发现通过 linestyle ='dashed'创建了一个虚线,所以我们非常感谢您将数据放在破折号之间。

关于标签的类似内容已经存在于Matplotlib中 - 正如我在the contour line demo中看到的那样。

Matplotlib Contour 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。

enter image description here

1 个答案:

答案 0 :(得分:1)

使用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")

收率:

plot

您可以使用偏移来获得更令人满意的结果。