在条形图中使用yerr时的ValueError和使用Pandas的pivot_table

时间:2018-04-23 20:42:07

标签: python pandas matplotlib

我正在尝试在pandas中使用yerr的{​​{1}}地块绘制错误栏(使用bar)。

到目前为止我有这个代码:

pivot_table

但是会显示以下错误:

from io import StringIO
import pandas as pd
import matplotlib.pyplot as plt

txt = u'''Category    COLUMN1         COLUMN2     COLUMN3    
A          0.5               3          Cat1   
B          0.3               5          Cat1 
C          0.7               4          Cat1
A          0.4               3          Cat2
B          0.8               5          Cat2
C          0.3               4          Cat2
'''

df = pd.read_table(StringIO(txt), sep="\s+")

order = ['Cat2', 'Cat1']
suborder = list("BAC")

df2 = pd.pivot_table(df,index='COLUMN3',columns='Category',values='COLUMN2').loc[order]
df2 = df2[suborder]
df2.plot(kind='bar', yerr=pd.pivot_table(df, index='COLUMN3',columns='Category',values='COLUMN1').values)

plt.legend(bbox_to_anchor=(1.3, 0.5))

plt.show() 

情节输出如下:

without error bars

使用 File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 2961, in extract_err raise ValueError("err must be [ scalar | N, Nx1 " ValueError: err must be [ scalar | N, Nx1 or 2xN array-like ] 绘制没有误差线的图表会产生此输出:

simple  plot

关于问题(防止显示错误条)的任何想法可能是?

1 个答案:

答案 0 :(得分:1)

您需要重新索引您的yerr数据帧,以匹配您的源数据帧df2。

<?php

function renderForm($ArtistName = '', $error = '', $ArtistID = '')
{
    // ...
}

if (isset($_GET['ArtistID'])) {
    if (isset($_POST['submit'])) {
        if (is_numeric($_GET['ArtistID'])) {
            $ArtistID = $_GET['ArtistID'];
            $ArtistName = htmlentities($_POST['ArtistName'], ENT_QUOTES);
            if ($ArtistName == '') {
                $error = 'ERROR: Please fill in all required fields!';
                renderForm($ArtistName, $error, $ArtistID);
            } else {
                if ($stmt = $conn->prepare("UPDATE Artists SET ArtistName = ? WHERE ArtistID=?")) {
                    $stmt->bind_param("s", $ArtistName);
                    $stmt->execute();
                    $stmt->close();
                } else {
                    echo "ERROR: could not prepare SQL statement.";
                }
            }
        }
    }
}

输出:

enter image description here