![](/img/trans.png)
[英]Python: seaborn pointplot and boxplot in one plot but shifted on the x-axis
[英]How to set the range of x-axis for a seaborn pointplot?
我創建了一個pointplot()
,但無法更改x軸限制。 盡管我的數據僅包含9個月,但我想在軸上顯示所有12個月。
fig,ax = plt.subplots(figsize=(12,4))
sns.pointplot(data=tr_df, x='Month', y='numOfTrips', hue='Year', ax=ax, palette='nipy_spectral')
# sns.plt.xlim(0, 12) # AttributeError: module 'seaborn' has no attribute 'plt'
# ax.set_xlim=(0, 12) # does nothing
ax.set(xlim=(0, 12))
ax.set(title="Number of trips each month")
我究竟做錯了什么?
編輯:用於創建繪圖的數據
Year Month numOfTrips
0 2011 7 2608
1 2011 8 33579
2 2011 9 34756
3 2011 10 31423
4 2011 11 20746
5 2012 3 12240
6 2012 4 37637
7 2012 5 46056
8 2012 6 48315
9 2012 7 61659
10 2012 8 75443
11 2012 9 73012
12 2012 10 67372
13 2012 11 40862
14 2013 4 56625
15 2013 5 88105
16 2013 6 99301
17 2013 7 92504
恕我直言,seaborn的pointplot
不是您想要的那種圖。
我建議使用一個簡單的lineplot
,然后嘗試按預期設置xlims:
fig,ax = plt.subplots(figsize=(12,4))
sns.lineplot(data=tr_df, x='Month', y='numOfTrips', hue='Year', ax=ax, palette='nipy_spectral')
ax.set(xlim=(0, 12))
ax.set(title="Number of trips each month")
導致
但是,我也建議在此上下文中將xticks設置為具有12個值的某些列表,而0 ... 12具有13個 ... ;-)
這有點駭人聽聞,但似乎可行。 我認為問題在於, pointplot
忽略軸的數值,並將其視為序數。 此代碼是一個手動替代:
fig,ax = plt.subplots(figsize=(12,4))
sns.pointplot(data=tr_df, x='Month', y='numOfTrips', hue='Year', ax=ax, palette='nipy_spectral')
ax.set_xticks(range(-3,10))
ax.set_xticklabels(range(12))
ax.set(title="Number of trips each month")
您基本上是在強迫繪圖在左右添加更多的刻度(使用負值),然后將所有標簽重命名為1到12。
看來問題在於,您的數據僅在第3個月到第11個月之間變化。然后,月份索引從3開始,這對應於xmin
。 一個使用一些隨機數據(在添加數據之前生成的數據)顯示此示例的示例是
import seaborn as sns
import pandas as pd
import numpy as np
y = [2011,2012,2013]
years = []
months = []
trips = []
np.random.seed(0)
for ii in range(27):
years.append(y[ii / 9])
months.append(ii % 9+3)
trips.append(np.random.randint(0,10)+(ii / 12)*10)
tr_df = pd.DataFrame({'Month':months, 'Trips':trips, 'Year':years})
fig,ax = plt.subplots(figsize=(12,4))
sns.pointplot(data=tr_df, x='Month', y='Trips', hue='Year', ax=ax,
palette='nipy_spectral', scale=0.7)
ax.set(xlim=(0, 12))
ax.set(title="Number of trips each month")
plt.show()
這將產生
解決此問題的最簡單方法(盡管它不能修復基礎數據,並且在所有情況下都無法使用)只是手動設置限制以解決偏移量-
ax.set(xlim=(-0.5, 8.5))
哪個會給你
如果您要包括少於最小值(即0,1,2)的xticks
, xticklabels
可以手動設置xticks
和xticklabels
ax.set_xticks(range(-3,9))
ax.set_xticklabels(range(0,12))
哪個會給你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.