簡體   English   中英

如何使用 Python Matplotlib 旋轉軸上的數字

[英]How to rotate the numbers on Axes using Python Matplotlib

有一個用 Matplotlib 繪制的散點圖,它的點比底部軸可以包含的點多,所以數字開始相互重疊,有沒有辦法將它們旋轉到一定程度或至少使它們垂直? 查看文檔,我找到了一種旋轉標簽的方法,但是否也可以旋轉數字?

我想到的最終結果是這樣的:

最后結果

如果這是不可能的,有沒有辦法只顯示指定范圍的數字,並隱藏所有點的確切 x 坐標? (如果我使用預先指定的數字,這正是我得到的行為,例如,如果 x 軸是從 0 到 20,則將 0、5、10、15 和 20 放在 x 軸上。

但是在這個圖中,我從 api(實時繪圖)獲取點,因此這些點是連續添加的,並且由於某些原因,matplotlib 的行為有所不同,並且沒有將我在 x 軸上指定的范圍限制從開始。 相反,它不斷將所有數字的 x 坐標放在 x 軸上,使它們重疊。

import requests
import matplotlib.pyplot as plt
from matplotlib import animation

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

xs = []
ys = []

def get_current_location(i):
  response = requests.get("http://api.open-notify.org/iss-now.json")
  response_json = response.json()
  if(response.status_code == 200):
    location_axes.clear()
    xs.append(response_json['iss_position']['longitude'])
    ys.append(response_json['iss_position']['latitude'])
    location_axes.scatter(
      xs,
      ys
    )
  else:
    raise ConnectionError("A connection error occured while retrieving the data")

location_axes.set_xlim([-180,180])
location_axes.set_ylim([-90,90])
plt.grid(True)
# plt.xtick(rotation=45)

anim = animation.FuncAnimation(fig, get_current_location, interval=1000)

plt.show()

你可以通過以下方式做到這一點:

plt.xtick(rotation=45)

如果您希望它是垂直的,您還可以執行以下操作:

plt.xticks(rotation='vertical')

您可以在以下文檔中閱讀有關輪換的更多信息:

https://matplotlib.org/3.1.1/gallery/ticks_and_spines/ticklabels_rotation.html

https://kite.com/python/answers/how-to-rotate-axis-labels-in-matplotlib-in-python

編輯

添加代碼后,請注意您應該執行以下操作,因為您希望對Axes對象執行操作:

location_axes.tick_params(axis='x', rotation=45)

將此添加到您在動畫期間調用的函數中:

def get_current_location(i):
  response = requests.get("http://api.open-notify.org/iss-now.json")
  response_json = response.json()
  if(response.status_code == 200):
    location_axes.clear()
    xs.append(response_json['iss_position']['longitude'])
    ys.append(response_json['iss_position']['latitude'])
    location_axes.scatter(
      xs,
      ys
    )
    location_axes.tick_params(axis='x', rotation=45)
  else:
    raise ConnectionError("A connection error occured while retrieving the data")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM