【问题标题】:How to plot a simple dataframe with different variables with different colors如何绘制具有不同颜色的不同变量的简单数据框
【发布时间】:2020-01-28 09:50:55
【问题描述】:

大家早上好,我的问题是数据框的图形表示。我的数据框类似于下面显示的这个

     Country  Year    average_man      average_woman
0         I1  2015       9.500000           3.663500
1         I1  2016       8.000000           4.810500
2         I2  2015      12.181818           3.514545
3         I2  2016      14.727273           2.815000

我想在一个图表中表示所有报告的信息,但我不知道如何将更多变量分配给同一轴。 现在我尝试绘制 average_mencountry 但我无法为每年的每个点分配不同的颜色。 例如 2015 年的蓝色和 2016 年的红色。

我的情节:

我的代码:

plt.scatter(df['average_man'], df['average_woman'], cmap= df['Year'])

plt.show()

预期输出

【问题讨论】:

    标签: python dataframe matplotlib plot scatter-plot


    【解决方案1】:

    你可以试试这个:

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    
    # Method 1, to plot individual columns
    # a scatter plot 
    df.plot(kind='scatter',x='average_man',y='average_woman',color='red')
    plt.show()
    
    # Method 2, To plot all columns separately
    df.plot(subplots=True)
    plt.tight_layout()
    plt.show()
    
    #Method 3, preferred
    data = np.random.rand(10,4)
    data[:,0]= np.arange(10)
    df = pd.DataFrame(data, columns=["X", "A", "B", "C"])
    axis = df.plot(x="X", y="A", kind="bar")
    df.plot(x="X", y="B", kind="bar", ax=axis, color="C2")
    df.plot(x="X", y="C", kind="bar", ax=axis, color="C3")
    plt.show()
    

    【讨论】:

    • 如果我尝试 x='average_man' 和 y='country' 我得到 TypeError: no numeric data to plot
    • 检查df['average_man']df['average_woman']的数据类型
    • 都是小数
    • 使用df["average_man"] = pd.to_numeric(df["average_man"])更改类型
    • 看看预期的输出
    【解决方案2】:

    我制作了一本将颜色与国家/地区相关联的字典:

    import matplotlib.pyplot as plt
    import pandas as pd
    
    # read csv
    df = pd.read_csv('test2.txt', delim_whitespace=True)
    
    # find all unique countries, which shall correspond to a color
    countries = df['Country'].unique()
    custom_colors = ['r','b','g','orange']
    
    # create a dictionary associating a color to a country
    col_dict = {country:custom_colors[i] for i, country in enumerate(countries)}
    
    # extend dataframe by new column with country colors
    df['country_colors'] = [col_dict[country] for country in df['Country']]
    
    
    # plot scatteplot while using c= as a container for colors.
    # This is what makes scatter special: color argument can be a container
    # of many different colors
    fig, ax = plt.subplots(figsize=(7,4))
    
    X,Y,col = df['average_man'], df['Country'], df['country_colors']
    ax.scatter(X,Y,c=col)
    

    我的代码中的 cmets 应该可以解释一切。但总的想法是找到所有独特的国家,将颜色与所有独特的国家相关联,然后在 DataFrame 中添加一个新列,在正确的位置使用正确的颜色:例如所有带有“I1”的行在数据框中都有颜色“r”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多