【问题标题】:How can I draw a radar chart and bar graph in the subplot in Python?如何在 Python 的 subplot 中绘制雷达图和条形图?
【发布时间】:2021-05-01 11:59:46
【问题描述】:

我在 Python 的子图中放置雷达图和条形图时遇到问题。

我定义了 1 行 2 列来将每一列放入每个插槽中。

我试图处理这个过程,但我做不到。

我该怎么做?

这是我的雷达功能,如下所示。

def radar_chart(values=[]):

    labels=np.array(['Crew',
                     'Length',
                     'Wingspan',
                     'Height',
                     'WingArea'
                    ]
                   )
    
    
    angles=np.linspace(0, 2*np.pi, len(labels), endpoint=False)
    #print(angles)

    fig=plt.figure(figsize=(6,6))
    #plt.suptitle(title, y=1.04)
    for v in values:
        stats=np.array(ww2aircraft_df[ww2aircraft_df["Name"]==v][labels])[0]
        #print(stats)
        ax = fig.add_subplot(111, polar=True)
        ax.plot(angles, stats, 'o-', linewidth=2, label = v)
        ax.fill(angles, stats, alpha=0.25)
        ax.set_thetagrids(angles * 180/np.pi, labels)

    ax.grid(True)
    #plt.legend(loc="upper right",bbox_to_anchor=(1.2,1.0))
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.10),
      fancybox=True, shadow=True, ncol=1, fontsize=13)

这是我的代码 sn-ps 如下所示。

f,a = plt.subplots(1,2,figsize=(24,10))

radar_chart(values=ww2aircraft_df_top_5["Name"])

graph_1 = sns.barplot(data = ww2aircraft_df_top_5, 
            x = "MaxSpeed", 
            y = "Name" , ax = a[1])
show_values_on_bars(graph_1, "h", 0.3)

plt.suptitle('Top 5 fastest of WW2 warplane by their features', 
             fontsize=20, 
             fontweight="semibold",
            )

plt.tight_layout()
plt.savefig('images/image10.png', bbox_inches = "tight")
plt.show()

【问题讨论】:

    标签: python bar-chart subplot figure radar-chart


    【解决方案1】:

    可能的解决方案如下:

    数据集可以在HERE找到

    # pip install matplotlib
    # pip install pandas
    # pip install seaborn
    

    import csv
    import pandas as pd
    import numpy as np
    from math import pi
    import matplotlib.pyplot as plt
    from matplotlib.gridspec import GridSpec
    import seaborn as sns
    
    # read csv to dataframe
    df = pd.read_csv('ww2aircraft.csv', sep=';')
    
    # select top-5 rows by 'MaxSpeed' column
    df_top5_maxspeed = df.nlargest(5, 'MaxSpeed').reset_index(drop=True)
    
    # convert column values to float type
    df_top5_maxspeed['Length'] = df_top5_maxspeed['Length'].astype('float64')
    df_top5_maxspeed['Wingspan'] = df_top5_maxspeed['Wingspan'].astype('float64')
    
    # limit dataframe to required columns
    df_top5_maxspeed_data = df_top5_maxspeed[["Name","Crew","Length","Wingspan","Height","WingArea","MaxSpeed"]]
    
    df_top5_maxspeed_data
    


    def create_radar_chart(df):
        # limit data drame
        df = df.iloc[:, :-1]
        
        categories=list(df_top5_maxspeed_data)[1:-1]
        N = len(categories)
    
        angles = [n / float(N) * 2 * pi for n in range(N)]
        angles += angles[:1]
    
        ax = fig.add_subplot(gs[0, 0], polar=True)
    
        ax.set_theta_offset(pi / 2)
        ax.set_theta_direction(-1)
    
        plt.xticks(angles[:-1], categories, size=10)
    
        ax.set_rlabel_position(0)
        plt.yticks([10,20,30,40], ["10","20","30","40"], color="grey", size=10)
        plt.ylim(0,40)
        
        for row in range(0, len(df.index)):
            
            values=df.loc[row].drop(['Name']).values.flatten().tolist()
            values+= values[:1]
    
            ax.plot(angles, values, 'o-', linewidth=2, label = df.loc[row]["Name"])
            ax.fill(angles, values, alpha=0.2)
        
        ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.10),
              fancybox=False, shadow=False, ncol=1, fontsize=10, frameon=False)
        
        
    def create_bar_chart(df):
        ax = fig.add_subplot(gs[0, 1])
        df = df[['Name','MaxSpeed']]
        df.plot.bar(x='Name', y='MaxSpeed', ax = ax, legend=False)
        plt.xlabel("")
        
    

    # create plots area
    fig = plt.figure(figsize=(15, 5))
    gs = GridSpec(nrows=1, ncols=2, width_ratios=[1, 1], wspace=0.1)
    fig.suptitle('Top 5 fastest of WW2 warplane by their features', fontsize=16)
    
    # add charts
    create_radar_chart(df_top5_maxspeed_data)
    create_bar_chart(df_top5_maxspeed_data)
    
    # adjust space between title and charts
    plt.subplots_adjust(top=0.85)
    

    【讨论】:

      最近更新 更多