我創建了這個圖,我在左側“y 軸”上“觀察到大腸桿菌”,在右側“y 軸”上有“建模大腸桿菌”,在“x 軸”上有“日期”。
代碼是這樣的
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
source = "Sample_table.csv"
df = pd.read_csv(source, encoding = 'unicode_escape')
x = df['Date_1']
y1 = df['Obs_Ec']
y2 = df['Rain']
y3 = df['Mod_Ec']
# Plot Line1 (Left Y Axis)
fig, ax1 = plt.subplots(1,1,figsize=(10,6), dpi= 80)
# Plot Line2 (Right Y Axis)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.plot(x, y2, color='tab:blue', linewidth=2.0)
# Plot Line2 (Right Y Axis)
ax3 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax3.scatter(x, y3)
# Control limits of the y Axis
a,b = 0,80000
c,d = 0,80000
e,f = 0,35
ax1.set_ylim(a,b)
ax3.set_ylim(c,d)
ax2.set_ylim(e,f)
# Decorations
# ax1 (left Y axis)
ax1.set_xlabel('Date', fontsize=20)
ax1.set_ylabel('E. coli - cfu ml-1', color='tab:red', fontsize=20)
ax1.tick_params(axis='y',rotation=0, labelcolor='tab:red')
ax1.grid(alpha=.0)
ax1.tick_params(axis='both', labelsize=14)
# Plot the scatter points
ax1.scatter(x, y1,
color="red", # Color of the dots
s=50, # Size of the dots
alpha=0.5, # Alpha of the dots
linewidths=0.5) # Size of edge around the dots
ax1.scatter(0**np.arange(5), 0**np.arange(5))
ax1.legend(['Observed E. coli'], loc='right',fontsize=14, bbox_to_anchor=(0.2, -0.20))
ax3.scatter(x, y3,
color="green", # Color of the dots
s=50, # Size of the dots
alpha=0.5, # Alpha of the dots
linewidths=0.5) # Size of edge around the dots
ax3.scatter(0**np.arange(5), 0**np.arange(5))
ax3.legend(['Modelled E. coli'], loc='right',fontsize=14, bbox_to_anchor=(0.48, -0.20))
# ax2 (right Y axis)
ax2.set_ylabel("Rainfall - mm", color='tab:blue', fontsize=20)
ax2.tick_params(axis='y', labelcolor='tab:blue')
ax2.tick_params(axis='both', labelsize=15)
ax2.set_xticks(np.arange(1, len(x), 4))
ax2.set_xticklabels(x[0::4], rotation=15, fontdict={'fontsize':10})
ax2.set_title("SP051 - without SR (validation 2018-2020)", fontsize=22)
ax2.legend(['rainfall'], loc='right',fontsize=14, bbox_to_anchor=(1.05, -0.20))
fig.tight_layout()
plt.show()
但是這段代碼給了我下面的這個圖:

我想改變這個情節中的三件事:
- 首先,將藍線圖轉換為條形圖。
- 其次,更重要的是,我想讓代表降雨的條形圖顯示在圖的頂部
- 第三,我需要通過使“ax3 散點圖”簡單地共享左側的“y 軸”來消除右側“y 軸”上的黑色刻度線。
我想創建的圖的一個例子是下面的圖,但我將使用散點圖而不是線,如上圖所示:

資料
資料可以在這里下載:
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/317780.html
標籤:Python 熊猫 matplotlib y轴 x轴
下一篇:按不同類別堆疊條形圖顏色
