[英]How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?
您可以將twinx()
方法與 seaborn 一起使用來創建一個單獨的 y 軸,一個用於線圖,另一個用於條形圖。 要控制繪圖的樣式(seaborn 的默認樣式為darkgrid),您可以使用 set_style 方法並指定首選主題。 如果您設置style=None
它會重置為沒有網格線的白色背景。 您也可以嘗試whitegrid
。 如果要進一步自定義網格線,可以使用ax2.grid(False)
在軸級別上進行。
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
matplotlib.rc_file_defaults()
ax1 = sns.set_style(style=None, rc=None )
fig, ax1 = plt.subplots(figsize=(12,6))
sns.lineplot(data = df['y_var_1'], marker='o', sort = False, ax=ax1)
ax2 = ax1.twinx()
sns.barplot(data = df, x='x_var', y='y_var_2', alpha=0.5, ax=ax2)
您必須刪除第二個軸的網格線。 添加到代碼ax2.grid(False)
。 但是,第二個軸的 y-ticks 不會與第一個 y 軸的 y-ticks 對齊,如下所示:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0,1,size=10)), color='g')
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(0,17,size=10)), color='r')
ax2.grid(False)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.