【问题标题】:matplotlib.pyplot non numeric barplotmatplotlib.pyplot 非数字条形图
【发布时间】:2019-08-10 05:05:20
【问题描述】:

我有 2 个问题

首先 当我得到“Empty 'DataFrame': no numeric data to plot”时,有没有办法对这个数据框进行条形图(未堆叠)?

df=pd.DataFrame({'midterm':['A','B','B','D'],'Final':['C','A','D','B']}, index=['math', 'sport', 'History', 'Physics'])

第二个问题: 我手动绘制数据框的数据,如

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame({'midterm':['A','B','B'],'Final':['C','A','D']}, index=['math', 'sport', 'History'])

fig, ax = plt.subplots()
index = np.asarray([1,10])
width=0.5
plt.bar(index, df.iloc[0,:], width,label='Math')
plt.bar(index+width, df.iloc[1,:], width, label='Sport')
plt.bar(index+2*width, df.iloc[2,:], width, label='History')
xticks=['midterm','final']
plt.xticks=(index,xticks)
plt.legend()
plt.show()

What the code produces is here

这有两个问题, - 首先,A、B、C、D 无序 - 其次,y 轴从点 0,0 开始,这使得该图中 C 级的条形根本不可见

what i aim to do is here

【问题讨论】:

  • 以下答案是否解决了您的问题?
  • 是的,这真的很有帮助,谢谢

标签: python dataframe matplotlib bar-chart


【解决方案1】:

我会回答你的第二个问题。您应该将您的问题限制为单个查询。我会将成绩映射到整数上,然后设置 y 刻度。为此,我定义了一个映射字典和一个函数mapping,它采用字母等级并将它们转换为条形图高度的整数值。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({'midterm':['A','B','B'],'Final':['C','A','D']}, index=['math', 'sport', 'History'])
map_dict = {'A': 1, 'B': 2, 'C': 3, 'D':4}

def mapping(keys):    
    values = [map_dict[i] for i in keys]
    return values

fig, ax = plt.subplots()
index = np.asarray([1,10])
width=0.5
plt.bar(index, mapping(df.iloc[0,:]), width,label='Math')
plt.bar(index+width, mapping(df.iloc[1,:]), width, label='Sport')
plt.bar(index-width, mapping(df.iloc[2,:]), width, label='History')
xticks=['midterm','final']
ax.set_yticks(range(1, 5))
ax.set_yticklabels(map_dict.keys())
plt.legend()

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2023-03-14
    • 2021-03-12
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    相关资源
    最近更新 更多