简体   繁体   English

用循环生成几个子图

[英]Generate several subplots with a loop

I want to show all average temperatures of each month in a small chart for every year.我想在每年的小图表中显示每个月的所有平均温度。 My first issue is printing the legend for the colder (blue) and warmer (respectively red) temperatures and giving colour to the chart itself.我的第一个问题是打印较冷(蓝色)和较暖(分别为红色)温度的图例,并为图表本身赋予颜色。 My second issue is connected with looping through the data, ending in getting the following error: TypeError: unsupported operand type(s) for /: 'tuple' and 'int' .我的第二个问题与循环遍历数据有关,最终出现以下错误: TypeError: unsupported operand type(s) for /: 'tuple' and 'int' The amount of the years doesn't always have to be an even number.年数并不总是必须是偶数。 How can I nicely represent that in the loop?我怎样才能在循环中很好地表示它?

How can I nake the chart like the picture underneath, including the coloured legend and chart.我怎样才能使图表像下面的图片一样,包括彩色图例和图表。

What I want:我想要的是:

  • displaying all the years with all average temperatures of each month显示所有年份以及每个月的所有平均温度
  • coloured legend and chart彩色图例和图表
  • (It doesn't matter whether matloblib or seaborn) (无论是 matloblib 还是 seaborn 都没有关系)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
d = {'year': [2001, 2001, 2001, 2001, 
              2002, 2002, 2002, 2002],
     'month': [1, 2,3,4,
              1,2,3,4],
     'temperature': [10,20,15,20,
                     20,10,5,10]}
df = pd.DataFrame(data=d)

df.head()


fig, axs = plt.subplots(int(len(df.year.unique()) / 2), int(len(df.year.unique()) / 2))

for i in enumerate(df.year.unique()):
    for j in range(int(i/2)):
        for k in range(int(i/2)):
            month = df['month'].unique()
            temperature = df[df['year'] == i].groupby('month')['temperature'].mean().values
            axs[j][k].bar(month, temperature)
plt.show()
    


TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

在此处输入图片说明

Seaborn with its facetgrid integrated plots gets you quite far. Seaborn 及其 facetgrid 集成图可以让您走得更远。 Plotting years in rows and columns like this is as simple as just using col="year", col_wrap=10 .像这样在行和列中绘制年份就像使用col="year", col_wrap=10一样简单。

In seaborn we prefer to use the facetgrid enabled plotting functions since they are flexible, like shown here in this example with catplot .在 seaborn 中,我们更喜欢使用支持 facetgrid 的绘图函数,因为它们很灵活,就像在这个示例中使用catplot

Here's an example, with some random data to fill out这是一个例子,有一些随机数据要填写

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

years = np.arange(1990, 2022, 1).reshape((-1, 1))
months = np.array([5, 6, 7, 8]).reshape((1, 4))
years, months = (np.broadcast_arrays(years, months))

d = {'year': years.flatten(),
     'month': months.flatten(),
     'temperature': np.random.randint(0, 25, size=years.size),
    }
df = pd.DataFrame(data=d)



fg = sns.catplot(data=df, kind='bar', x='month', y='temperature', hue='temperature',
                 palette='Reds', col='year', col_wrap=10,
                 height=2, aspect=0.8, dodge=False, ci=None);
fg.set_titles(col_template="{col_name}");
fg.legend.remove()

# Hackily add a colorbar too
norm = plt.Normalize(df.temperature.min(), df.temperature.max())
sm = plt.cm.ScalarMappable(cmap="Reds", norm=norm)
sm.set_array([])

cax = fg.figure.add_axes([0.96, .12, .02, .8])
fg.figure.colorbar(sm, cax=cax);

The fg is the facetgrid that we can use to access indidivual axes and do further tweaks. fg是我们可以用来访问单个轴并进行进一步调整的 facetgrid。 All axes would be accessed by using a loop over fg.axes .所有轴都可以通过使用fg.axes的循环来访问。

The absolute weak point here is that seaborn doesn't support continuous hue coloring by values (It's a future project as of this writing, see this issue ).这里的绝对弱点是 seaborn 不支持按值进行连续色调着色(这是撰写本文时的一个未来项目,请参阅本期)。 So we don't have great hue interpolation and no continuous color bar automatically.所以我们没有很好的色调插值,也没有自动连续的颜色条。

However, I've added a colorbar workaround - all credit to this answer .但是,我添加了一个 colorbar 解决方法 - 所有功劳都归功于这个答案 It must be said that the hues and the colorbar are not exactly in sync.必须说色调和颜色条并不完全同步。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM