绘制DataFrame的选择行和列(python)

时间:2018-12-04 08:41:35

标签: python pandas dataframe bar-chart

我搜索了周围,但没有找到执行此操作的确切方法。我有几个棒球队及其统计数据。如下所示:

   RK   TEAM         GP  AB   R   H    2B  3B  HR   TB   RBI  AVG OBP  SLG   OPS
    1   Milwaukee    163 5542 754 1398 252 24  218  2352 711  .252.323 .424 .747
    2   Chicago Cubs 163 5624 761 1453 286 34  167  2308 722  .258.333 .410 .744
    3   LA Dodgers  163  5572 804 1394 296  33  235 2461 756  .250.333 .442 .774
    4   Colorado    163  5541 780 1418 280  42  210 2412 748  .256.322 .435 .757
    5   Baltimore   162  5507 622 1317 242  15  188 2153 593  .239.298 .391 .689

我希望能够在X轴上绘制两个团队,然后在Y轴上绘制3个指标(例如R,H,TB),并且两个团队以条形图格式并排。我还无法弄清楚该怎么做。有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

我的方法是创建一个新的数据框,其中仅包含您要绘制的列:

import pandas as pd
import matplotlib.pyplot as plt


data = [[1, 'Milwaukee', 163, 5542, 754, 1398, 252, 24, 218, 2352, 711, .252, .323, .424, .747],
        [2, 'Chicago Cubs', 163, 5624, 761, 1453, 286, 34, 167, 2308, 722, .258, .333, .410, .744],
        [3, 'LA Dodgers', 163, 5572, 804, 1394, 296, 33, 235, 2461, 756, .250, .333, .442, .774],
        [4, 'Colorado', 163, 5541, 780, 1418, 280, 42, 210, 2412, 748, .256, .322, .435, .757],
        [5, 'Baltimore', 162, 5507, 622, 1317, 242, 15, 188, 2153, 593, .239, .298, .391, .689]]

df = pd.DataFrame(data, columns=['RK', 'TEAM', 'GP', 'AB', 'R', 'H', '2B', '3B', 'HR', 'TB', 'RBI', 'AVG', 'OBP', 'SLG', 'OPS'])

dfplot = df[['TEAM', 'R', 'H', 'TB']].copy()

fig = plt.figure()

ax = fig.add_subplot(111)

width = 0.4
dfplot.plot(kind='bar', x='TEAM', ax=ax, width=width, position=1)

plt.show()

这将创建以下输出:

Plot of teams with multiple y-axes values