![](/img/trans.png)
[英]format x-axis values and show them only under the scatter plot value - matplotlib in Python
[英]How to show x-axis values on scatter plot?
我在 google co-lab 上做了一個散點圖 plot,但看不到 x 軸。 這是在 python 中,使用 matplotlib 庫。
import matplotlib.pyplot as plt
import pandas as pd
from google.colab import drive
drive.mount('/content/drive')
weather_data = '/content/drive/MyDrive/Austin Weather Data/austin_weather.csv'
weather = pd.read_csv(weather_data)
ausweather = weather[['Date', 'TempAvgF']]
ausweather.head()
x = weather['Date']
y = weather['TempAvgF']
plt.scatter(x, y)
plt.rcParams["figure.figsize"] = (30,25)
plt.show
出現散點圖 plot,但在 x 軸標簽應位於的位置有 2 個黑條。
我沒有您正在使用的數據集,但我使用給定的簡單數組運行代碼。 它顯示了 x 軸和 y 軸。 我希望這會起作用,或者如果它不起作用,請分享數據集。 代碼:
import matplotlib.pyplot as plt
import pandas as pd
# from google.colab import drive
# drive.mount('/content/drive')
# weather_data = '/content/drive/MyDrive/Austin Weather
#Data/austin_weather.csv'
# weather = pd.read_csv(weather_data)
# ausweather = weather[['Date', 'TempAvgF']]
# ausweather.head()
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,4,9,16,25,36,49,64,81,100]
plt.scatter(x, y)
plt.rcParams["figure.figsize"] = (30,25)
plt.show
您看到黑條的原因是因為所有 1300 多個日期都寫得非常接近。 這可能不是正確的設置。 只需將 X 軸更改為僅顯示年份(一個選項),這樣就可以處理了。 下面是更新后的代碼。 但是,請注意,我是在本地運行的,而不是在 google colab 上運行的。 但是,由於變化是在 plt 軸上進行的,所以應該沒問題。 您需要在plt.scatter()
之后添加 4 行,如下面的代碼所示...可以在此處找到有關日期格式化程序的更多選項
我的代碼:
import matplotlib.pyplot as plt
import pandas as pd
#from google.colab import drive #Commented as I am running this locally
#drive.mount('/content/drive') #Commented as I am running this locally
#weather_data = '/content/drive/MyDrive/Austin Weather Data/austin_weather.csv'#Commented as I am running this locally
weather = pd.read_csv('austin_weather.csv')
ausweather = weather[['Date', 'TempAvgF']]
ausweather.head()
x = weather['Date']
y = weather['TempAvgF']
ax = plt.scatter(x, y)
#### New code here ####
import matplotlib.dates as mdate
locator = mdate.YearLocator()
plt.gca().xaxis.set_major_locator(locator)
plt.gca().xaxis.set_major_formatter(mdate.DateFormatter('%Y'))
#### New code end ####
plt.rcParams["figure.figsize"] = (5,8)
plt.show
我的 output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.