【问题标题】:How to plot a Arrow and Range plot in Python?如何在 Python 中绘制箭头和范围图?
【发布时间】:2021-08-04 09:29:36
【问题描述】:

Arrow plots 是一种相对较新的图表类型。它们显示了不同类别(例如国家、政党)的数据点(例如预期寿命、选举结果)在两个日期(例如几十年、几年、几天)之间是如何变化的。箭头图正好显示两个日期。如果要显示数据点的多个时间点,请考虑使用折线图。如果您的重点是点之间的间隙而不是它们之间经过的时间,那么范围图是更好的选择。如果您没有时间点并且只想在一条线上显示一个或多个点,请考虑使用点图。

来源:economist- Americans are getting more nervous about what they say in public

Source: bundestag.de Get the data

我只是想知道是否有任何 python 包可用于绘制类似的箭头图。我的可视化知识是最少的。我不是要求准确复制上述情节,我们将非常感谢类似的情节。

我对新的想法和方法持开放态度,并希望在开始之前先试一试

如果是,是否可以用 Python 绘制上面的图,哪个包将用于绘制上面的图?任何人都可以对用 Python 绘制上述情节有所了解吗?我很乐意收到您的任何线索。

【问题讨论】:

    标签: python matplotlib data-visualization


    【解决方案1】:

    对于这种类型的图,我认为最耗时的类型是 MPL,但我编写代码的方式是模仿预期输出的第二个示例。基本上,它是用箭头和注释创建的。

    import pandas as pd
    import numpy as np
    import io
    
    data = '''
    Party 2009 2013
    CDU/CSU 33.8 41.5
    SPD 23.0 25.7
    LINKE 11.9 8.6
    GRÜNE 10.7 8.4
    FDP 14.6 4.8
    '''
    
    df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
    
    import matplotlib.pyplot as plt
    from matplotlib import colors as mcolors
    colors = mcolors.TABLEAU_COLORS
    
    fig, ax = plt.subplots(figsize=(10,4))
    plt.rcParams.update({'axes.spines.top': False, 'axes.spines.right': False})
    
    for (idx,row), c in zip(df.iterrows(),colors):
        cols = colors.keys()
        ax.arrow(row['2009'], idx, row['2013']-row['2009'], 0, head_width=0.2, head_length=0.7, width=0.03, fc=c, ec=c)
        if row['2009'] < row['2013']:
            ax.annotate('{}'.format(row['2009']), xy=(row['2009'], idx), xytext=(row['2009']-2.5,idx-0.05), xycoords='data', color=c)
            ax.annotate('{}'.format(row['2013']), xy=(row['2013'], idx), xytext=(row['2013']+0.9,idx-0.05), xycoords='data', color=c)
        else:
            ax.annotate('{}'.format(row['2009']), xy=(row['2009'], idx), xytext=(row['2009']+0.5,idx-0.05), xycoords='data', color=c)
            ax.annotate('{}'.format(row['2013']), xy=(row['2013'], idx), xytext=(row['2013']-2.5,idx-0.05), xycoords='data', color=c)
    
        ax.set_yticks(np.arange(len(df)))        
        ax.set_yticklabels(df['Party'])
        ax.grid()
        ax.set_xlim(-5,45)
        ax.tick_params('x', length=0, which='major')
        ax.tick_params('y', length=0, which='major')
    
    ax.annotate('2009', xy=(0.25,0.85), xytext=(0.25,0.93), xycoords='figure fraction', arrowprops=dict(arrowstyle='-'))
    ax.annotate('2013', xy=(0.45,0.85), xytext=(0.45,0.93), xycoords='figure fraction', arrowprops=dict(arrowstyle='-'))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      相关资源
      最近更新 更多