无法为matplotlib子图绘制图例/轴

时间:2015-02-21 18:49:19

标签: python matplotlib plot

所以我有一些我想在matplotlib中绘制的数据。所以我的数据有一些我想要绘制的变量。我想要做的是为每个位置制作一个子图,每个子图都有多个组,我想要显示值如何随时间变化。我的数据的一个例子是:

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

df = pd.DataFrame({
               "GEO": [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
               "year": [2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011],
               "GROUP": ['doctor','doctor','Knight','Knight','Wizard','Wizard','doctor','doctor','Knight','Knight','Wizard','Wizard','doctor','doctor','Knight','Knight','Wizard','Wizard'], 
                "Value": random.sample(xrange(100), 18)
})

provs = df["GEO"].unique()
f, axarr = plt.subplots(len(provs), sharex=True, sharey=True)
myplot = 0

for prov in provs:
    groups = df.loc[df["GEO"] == prov, "GROUP"].unique()
    axarr[myplot].set_title(prov)
    for group in groups:
        x = df.loc[(df["GEO"] == prov) & (df["GROUP"] == group), "year"].tolist()
        y = df.loc[(df["GEO"] == prov) & (df["GROUP"] == group), "Value"].tolist()
        axarr[myplot].plot(x, y, label=group)    
    myplot = myplot + 1
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.xlabel('Year')
plt.ylabel('Amount in $')
plt.xlim(2010, 2011)
plt.show()

所以我有问题

1)尝试将X轴设置为显示年份(因此为2010年和2011年)而不是0 - 1

2)尝试将我的图例和轴标签置于中心位置(非常确定为子图做错了。)

plot

1 个答案:

答案 0 :(得分:0)

以下内容修复了x轴的问题,并将Y轴标签添加到所有图中。前者是由于在x轴上使用(默认情况下)科学记数法,具有偏移量。最容易使用set_xticks()覆盖并删除偏移量。通过将标签分别应用于每个图,而不是仅使用最后一个图来固定Y轴。

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

df = pd.DataFrame({
               "GEO": [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
               "year": [2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011,2010,2011],
               "GROUP": ['doctor','doctor','Knight','Knight','Wizard','Wizard','doctor','doctor','Knight','Knight','Wizard','Wizard','doctor','doctor','Knight','Knight','Wizard','Wizard'], 
                "Value": random.sample(xrange(100), 18)
})

provs = df["GEO"].unique()
f, axarr = plt.subplots(len(provs), sharex=True, sharey=True)
myplot = 0

for prov in provs:
    groups = df.loc[df["GEO"] == prov, "GROUP"].unique()
    axarr[myplot].set_title(prov)
    for group in groups:
        x = df.loc[(df["GEO"] == prov) & (df["GROUP"] == group), "year"].tolist()
        y = df.loc[(df["GEO"] == prov) & (df["GROUP"] == group), "Value"].tolist()

        axarr[myplot].ticklabel_format(style='plain', useOffset=False)
        axarr[myplot].plot(x, y, label=group)    
        axarr[myplot].set_ylabel('Amount in $')
        axarr[myplot].set_xticks([2010, 2011])

    myplot = myplot + 1


plt.xlabel('Year')  # Only on the final plot (bottom)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()