![](/img/trans.png)
[英]How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?
[英]How to plot seaborn lineplot and barplot on the same plot with same number of y-axes tickers and both y-axes aligned at 0 in Python
我無法使用來自“結果”dataframe 的數據在相同的 seaborn plot 上繪制線圖和條形圖(具有相同的 inexes),我將在下面顯示(帶有“a”數據、“b”數據和“百分位數”)在 Python。
當我分別對它們進行 plot 時,我能夠 plot 線圖很好(使用“a”數據),但是,我嘗試 plot(使用“b”數據)的條形圖的 x 軸值沒有顯示。 奇怪的是,我可以使用相同的數據 plot 一個線圖而沒有任何問題我正在嘗試使用('b'數據)plot 條形圖
當我嘗試在同一個 plot 上對它們進行 plot 時,x 軸從一個甚至不存在於“結果”dataframe 中的日期開始。
我什至嘗試將結果 dataframe 導出為 csv 並重新導入它以查看是否有效,但我遇到了同樣的問題。
我想達到的目標:
# Here is the 'a' and 'b' data that I start with
a = pd.read_csv(r'a.csv',sep=",", parse_dates=['date'], dayfirst=True, index_col=0)
b = pd.read_csv(r'b.csv',sep=",", parse_dates=['date'], dayfirst=True, index_col=0)
# After manipulating the data, here is the 'results' DataFrame I end up with
# Plotting them separately
# Plotting lineplot using 'a' column from 'results' DataFrame
sns.lineplot(data=result.iloc[:, 0], color="g")
# Plotting barplot using 'b' column from 'results' DataFrame
b_plot = sns.barplot(data=result, x=result.index, y=result.iloc[:, 2], color="b")
b_plot.xaxis.set_major_locator(md.YearLocator(base=4))
b_plot.xaxis.set_major_formatter(md.DateFormatter('%Y'))
b_plot.margins(x=0)
# Attempting to plot the lineplot and barplot on the same plot
matplotlib.rc_file_defaults()
ax1 = sns.set_style(style=None, rc=None)
fig, ax1 = plt.subplots(figsize=(12,6))
a_plot = sns.lineplot(data=result.iloc[:, 0], color="g", ax=ax1)
ax2 = ax1.twinx()
b_plot = sns.barplot(data=result, x=result.index, y=result.iloc[:, 2], color="b", ax=ax2)
b_plot.xaxis.set_major_locator(md.YearLocator(base=4))
b_plot.xaxis.set_major_formatter(md.DateFormatter('%Y'))
b_plot.margins(x=0)
編輯:我已經回答了以下問題
這是我在評論中建議的示例。
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame({'Day': [1, 2, 3, 4], 'Value': [3, 7, 4, 2], 'Value 2': [1, 7, 4, 5]})
f, ax = plt.subplots()
sns.barplot(data=data, x='Day', y='Value')
編輯:在此處使用點圖對齊條目。
sns.pointplot(data=data, x='Day', y='Value 2')
以下是我的問題的答案:
matplotlib.rc_file_defaults()
ax1 = sns.set_style(style=None, rc=None)
fig, ax1 = plt.subplots(figsize=(12,6))
ax2 = ax1.twinx()
# plot the bar plot and make the colours dependent on the values in a seperate column
result_date = result.reset_index()
palette = {"low":"lightgreen",
"mid":"darkseagreen",
"high":"green"}
b_plot = sns.barplot(data = result_date, x=result_date.iloc[:, 0],
y=result_date.iloc[:, 3], ax=ax1, hue='percentile', palette=palette, dodge = False)
# plot the lineplot
a_plot = sns.pointplot(data=result, x=result.index, y=result.iloc[:, 0], color="black", ax=ax2, markers = 'o', scale=0.4)
# set the x tickers to be those of the bar plot
ax1.set_xticks(np.arange(len(result_date)))
ax1.set_xticklabels(result_date.date.apply(lambda x: str(x.year)))
ax1.xaxis.set_major_locator(ticker.AutoLocator())
# align axis at 0, and get same number of ticks on both y-axes
max1 = np.nanmax(np.abs(ax1.get_ybound()))
max2 = np.nanmax(np.abs(ax2.get_ybound()))
nticks = 7
ax1.set_yticks(np.linspace(-max1, max1, nticks))
ax2.set_yticks(np.linspace(-max2, max2, nticks))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.