グリッド間隔を変更し、目盛りラベルを指定する 質問する

グリッド間隔を変更し、目盛りラベルを指定する 質問する

グリッド プロットにカウントをプロットしようとしていますが、その方法がわかりません。

欲しい:

  1. 5 間隔で点線のグリッドを配置する。

  2. 主要な目盛りラベルを 20 ごとにのみ配置する。

  3. 目盛りがプロットの外側にあること。

  4. グリッド内に「カウント」を表示します。

重複の可能性がある項目をチェックしました。ここそしてここ、しかし、それを理解することはできませんでした。

これが私のコードです:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

for x, y, count in data.values():

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.annotate(count, xy = (x, y), size = 5)
    # overwrites and I only get the last data point

    plt.close()
    # Without this, I get a "fail to allocate bitmap" error.

plt.suptitle('Number of counts', fontsize = 12)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.axes().set_aspect('equal')

plt.axis([0, 1000, 0, 1000])
# This gives an interval of 200.

majorLocator   = MultipleLocator(20)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(5)
# I want the minor grid to be 5 and the major grid to be 20.
plt.grid()

これが私が得たものです。

私が得たものは次のとおりです:

ベストアンサー1

コードにいくつか問題があります。

まず大きなものから:

  1. ループの反復ごとに新しい図と新しい軸を作成します →ループの外側にfig = plt.figure配置します。ax = fig.add_subplot(1,1,1)

  2. ロケーターを使用しないでください。正しいキーワードを使用してax.set_xticks()関数を呼び出します。ax.grid()

  3. を使用すると、plt.axes()再び新しい軸が作成されます。 を使用しますax.set_aspect('equal')

些細なこと: MATLABのような構文と目的の構文を混在させないでくださいplt.axis()ax.set_xlim(a,b)ax.set_ylim(a,b)

これは動作する最小限の例です:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which='both')

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

plt.show()

出力は次のようになります。

結果

おすすめ記事