簡體   English   中英

Python (twinx plot) 古怪圖

[英]Python (twinx plot) Wacky graph

編輯:圖表現在已修復,但我在繪制圖例時遇到了麻煩。 它僅顯示其中 1 個圖的圖例。 如下圖所示

我正在嘗試使用 twinx 繪制雙軸圖,但我面臨一些困難,如下圖所示。

歡迎任何輸入! 如果您需要任何其他信息,我很樂意為您提供。

在此處輸入圖片說明

與繪制 z 軸之前的原始圖像相比。

在此處輸入圖片說明

我不確定為什么我的圖表在繪制我的輔助 y 軸(粉紅色線)之前最初是這樣的,可以完美地看到收盤值圖表,但現在它似乎被切斷了。

這可能是由於我的數據如下。

鏈接到 testing1.csv: https : //filebin.net/ou93iqiinss02l0g

我目前擁有的代碼:

# read csv into variable
sg_df_merged = pd.read_csv("testing1.csv", parse_dates=[0], index_col=0)

# define figure
fig = plt.figure()

fig, ax5 = plt.subplots()
ax6 = ax5.twinx()

x = sg_df_merged.index
y = sg_df_merged["Adj Close"]
z = sg_df_merged["Singapore"]

curve1 = ax5.plot(x, y, label="Singapore", color = "c")
curve2 = ax6.plot(x, z, label = "Face Mask Compliance", color = "m")
curves = [curve1, curve2]

# labels for my axis
ax5.set_xlabel("Year")
ax5.set_ylabel("Adjusted Closing Value ($)")
ax6.set_ylabel("% compliance to wearing face mask")
ax5.grid #not sure what this line does actually

# set x-axis values to 45 degree angle
for label in ax5.xaxis.get_ticklabels():
    label.set_rotation(45)
ax5.grid(True, color = "k", linestyle = "-", linewidth = 0.3)

plt.gca().legend(loc='center left', bbox_to_anchor=(1.1, 0.5), title = "Country Index")
plt.show(); 

最初,我認為這是由於我的 excel 有整個空白行,但我已經刪除了可以在此處找到的行

另外,我試圖進行插值,但不知何故它不起作用。 非常歡迎對此提出任何建議

  • 僅刪除所有NaN行。 NaN仍然有很多行。
  • 為了讓matplotlib在兩個數據點之間繪制連接線,這些點必須是連續的。
  • 繪圖 API 未連接NaN值之間的數據
  • 這可以用通過轉換來處理pandas.Series到一個DataFrame ,並使用.dropna
  • 看到x已被刪除,因為它與yz的索引長度不匹配。 它們在.dropna之后更短。
  • y現在是一個單獨的數據.dropna ,其中使用了.dropna
  • z也是一個單獨的數據幀,其中使用了.dropna
  • 該圖的x-axis是各自的索引。
# read csv into variable
sg_df_merged = pd.read_csv("test.csv", parse_dates=[0], index_col=0)

# define figure
fig, ax5 = plt.subplots(figsize=(8, 6))
ax6 = ax5.twinx()

# select specific columns to plot and drop additional NaN
y = pd.DataFrame(sg_df_merged["Adj Close"]).dropna()
z = pd.DataFrame(sg_df_merged["Singapore"]).dropna()

# add plots with markers
curve1 = ax5.plot(y.index, 'Adj Close', data=y, label="Singapore", color = "c", marker='o')
curve2 = ax6.plot(z.index, 'Singapore', data=z, label = "Face Mask Compliance", color = "m", marker='o')

# labels for my axis
ax5.set_xlabel("Year")
ax5.set_ylabel("Adjusted Closing Value ($)")
ax6.set_ylabel("% compliance to wearing face mask")
    
# rotate xticks
ax5.xaxis.set_tick_params(rotation=45)

# add a grid to ax5
ax5.grid(True, color = "k", linestyle = "-", linewidth = 0.3)

# create a legend for both axes
curves = curve1 + curve2
labels = [l.get_label() for l in curves]
ax5.legend(curves, labels, loc='center left', bbox_to_anchor=(1.1, 0.5), title = "Country Index")

plt.show()

在此處輸入圖片說明

暫無
暫無

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

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