[英]How to get axes correct matplotlib
我有這張表,我想顯示兩個趨勢與日期。 我想顯示表格中股票價格的收盤價以及石油價格。 出於某種原因,我真的很難做到這一點。 這是我到目前為止所做的:
正如您可以清楚地看到的那樣,這不是我想要的......我不知道為什么我的 y 軸會以這種方式出現,我只想用 y 軸作為價格顯示這些列。 有人可以幫忙嗎?
這是該表上的 info 命令的結果。
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 91 entries, 2010-02-01 to 2020-09-01
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Open 91 non-null float64
1 High 91 non-null float64
2 Low 91 non-null float64
3 Close 91 non-null float64
4 Adj Close 91 non-null float64
5 Volume 91 non-null int64
6 Oil Price 91 non-null object
dtypes: float64(5), int64(1), object(1)
memory usage: 8.2+ KB
從stocksAndOil.info()
的輸出中可以看出, Close
列是float64
類型,這很好:pandas 將其值解釋為數字。
相反,列Oil Price
is object
:這意味着 pandas 將其值解釋為字符串,而不是數字。 換句話說,該值74.41
為Oil price
在2020-02-01
(上面的截圖的第一行)被解釋為字符串'74.41'
。
要解決,您需要將Oil price
列類型從str
轉換為float
:
stocksAndOil['Oil price'] = stocksAndOil['Oil price].astype(float)
檢查此代碼作為示例:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': [1, 2, 3],
'B': ['3', '2', '4']})
print(df.info())
fig, ax = plt.subplots()
ax.scatter(df['A'], df['B'])
plt.show()
正如您可以看到的,列'B'
只有str
值。 df.info()
的輸出是:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 3 non-null int64
1 B 3 non-null object
dtypes: int64(1), object(1)
memory usage: 100.0+ bytes
得到的情節是:
檢查 y 軸標簽: 2
介於3
和4
之間,所以這顯然是錯誤的。
為了解決我使用這個代碼:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': [1, 2, 3],
'B': ['3', '2', '4']})
df['B'] = df['B'].astype(float)
print(df.info())
fig, ax = plt.subplots()
ax.scatter(df['A'], df['B'])
plt.show()
df.info()
的輸出是:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 3 non-null int64
1 B 3 non-null float64
dtypes: float64(1), int64(1)
memory usage: 112.0 bytes
這次'B'
列具有float
值,結果圖是正確的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.