1

このグラフは Excel で作成されています。 ここに画像の説明を入力 matplotlib を使用して同じことを行うにはどうすればよいですか?

2 つのフォーマッターを追加する方法を意味します。

  • 月。

今、私はこのようなものを使用しています:

fig, ax = plt.subplots(1,1)
ax.margins(x=0)
ax.plot(list(df['Date']), list(df['Value']), color="g")
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y'))
plt.text(df["Date"].iloc[-1], df["Value"].iloc[-1], df["Value"].iloc[-1])
plt.title(title)
plt.get_current_fig_manager().full_screen_toggle()
plt.grid(axis = 'y')
plt.savefig('pict\\'+sheet.cell_value(row,1).split(',')[0]+'.png', dpi=300, format='png')
#plt.show()
plt.close(fig)

それは描く:

ここに画像の説明を入力

4

1 に答える 1

1

ラベルには主軸を使用し、yearラベルには副軸を使用する必要がありますmonth。次のようなものを使用して、2 次軸を生成できます。

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.dates as md

fig = plt.figure()
months = host_subplot(111, axes_class = AA.Axes, figure = fig)
plt.subplots_adjust(bottom = 0.1)
years = months.twiny()

次に、次の方法でセカンダリ軸を下に移動する必要があります。

offset = -20
new_fixed_axis = years.get_grid_helper().new_fixed_axis
years.axis['bottom'] = new_fixed_axis(loc = 'bottom',
                                      axes = years,
                                      offset = (0, offset))

最後に、プロットしてから、 と を使用して主軸と副軸の形式を調整しmd.MonthLocatorますmd.YearLocator。次のようなもので問題ありません。

months.xaxis.set_major_locator(md.MonthLocator(interval = 1))
months.xaxis.set_major_formatter(md.DateFormatter('%B'))
months.set_xlim([df['Date'].iloc[0], df['Date'].iloc[-1]])

years.xaxis.set_major_locator(md.YearLocator(interval = 1))
years.xaxis.set_major_formatter(md.DateFormatter('%H'))
years.set_xlim([df['Date'].iloc[0], df['Date'].iloc[-1]])

これらの 2 つの回答を確認してみてください。これらのコードをケースに適合させることは難しくありません。

于 2020-06-27T18:17:44.003 に答える