【问题标题】:matplotlib - dashed line between points if one condition is metmatplotlib - 如果满足一个条件,点之间的虚线
【发布时间】:2020-01-04 12:36:03
【问题描述】:

我正在使用 matplotlib 绘制绘图。我想要实现的是在满足一个条件时连接点。例如,如果我有如下数据框:

import os
import pandas as pd
import numpy as np

from matplotlib import pyplot as plt

df=pd.DataFrame({'dates': [2001, 2002, 2003, 2004, 2005, 2006], 'census_people': [306,327,352,478,250, 566], 'census_houses': [150,200,249,263, 180, 475]}) #I changed the dates from strings to ints

我可以使用以下代码创建这样的图:

plt.plot('dates','census_houses',data=df[df['dates'] < 2004] ,marker='o',color='orange', linewidth=2)
plt.plot('dates','census_houses',data=df[df['dates'] > 2002] ,marker='o',color='orange', linewidth=2, linestyle = '--')

剧情如下:

但是,我真正想要的是,例如,如果census_houses 大于 250,则使用虚线连接点。如何使用 matplotlib 实现这一点?欢迎任何建议和见解!谢谢~

【问题讨论】:

    标签: python-3.x pandas matplotlib


    【解决方案1】:

    这个效果可以通过应用剪切路径来实现。在这个例子中,我假设实线完全覆盖了虚线,所以只需要剪掉整线。

    在示例中,y 轴的特殊值设置为 220,使用了不同的颜色和非常粗的线条,以便更好地查看发生了什么。 Rectangle((x, y), width, height) 的参数将 y 设置为所需的截止值,x 位于最左侧的某个位置,width 确保 x + width 位于最右侧,height 是一个很大的正数剪辑在线上方,负剪辑在线下方。

    This post 有更多关于剪切路径的信息。

    import pandas as pd
    from matplotlib import pyplot as plt
    from matplotlib.patches import Rectangle
    
    def do_clipping(patches, special_y, keep_below=True, ax=None):
        ax = ax or plt.gca()
        xmin, xmax = plt.xlim()
        ymin, ymax = plt.ylim()
        height = ymax - ymin
        if keep_below:
            height = -height
        clip_rect = Rectangle((xmin, special_y), xmax - xmin, height,
                              transform=ax.transData)
        for p in patches:
            p.set_clip_path(clip_rect)
    
    df = pd.DataFrame({'dates': [2001, 2002, 2003, 2004, 2005, 2006],
                       'census_houses': [150, 200, 249, 263, 180, 475]})
    plt.plot('dates', 'census_houses', data=df, color='limegreen', linewidth=10, linestyle='--')
    plot_patches = plt.plot('dates', 'census_houses', data=df, color='crimson', linewidth=10)
    do_clipping(plot_patches, 220)
    plt.show()
    

    【讨论】:

    • 非常感谢您的回复!解决方案广受好评!我将尝试将您的代码应用于我自己的问题...
    猜你喜欢
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    相关资源
    最近更新 更多