Vin*_*ent 4 python matplotlib pandas seaborn
我想调整我的绘图代码以显示最小/最大条形,如下图所示:
我的代码是:
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
sns.set_style('darkgrid',{"axes.facecolor": ".92"}) # (1)
sns.set_context('notebook')
Delay = ['S1', 'S2', 'S3', 'S4']
Time = [87, 66, 90, 55]
df = pd.DataFrame({'Delay':Delay,'Time':Time})
print("Accuracy")
display(df) # in jupyter
fig, ax = plt.subplots(figsize = (8,6))
x = Delay
y = Time
plt.xlabel("Delay", size=14)
plt.ylim(-0.3, 100)
width = 0.1
for i, j in zip(x,y):
ax.bar(i,j, edgecolor = "black",
error_kw=dict(lw=1, capsize=1, capthick=1))
ax.set(ylabel = 'Accuracy')
from matplotlib import ticker
ax.yaxis.set_major_locator(ticker.MultipleLocator(10))
plt.savefig("Try.png", dpi=300, bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)
代码产生这个图:
我想添加的最小/最大是:
87 (60-90)
66 (40-70)
90 (80-93)
55 (23-60)
Run Code Online (Sandbox Code Playgroud)
预先感谢您的帮助。
seaborn.barplotax.barmatplotlib.pyplot.errorbarpython 3.11, pandas 1.5.3, matplotlib 3.7.0,seaborn 0.12.2import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# set edgecolor param (this is a global setting, so only set it once)
plt.rcParams["patch.force_edgecolor"] = True
# setup the dataframe
Delay = ['S1', 'S2', 'S3', 'S4']
Time = [87, 66, 90, 55]
df = pd.DataFrame({'Delay':Delay,'Time':Time})
# create a dict for the errors
error = {87: {'max': 90,'min': 60}, 66: {'max': 70,'min': 40}, 90: {'max': 93,'min': 80}, 55: {'max': 60,'min': 23}}
Run Code Online (Sandbox Code Playgroud)
seaborn.barplotseaborn.barplot将自动添加误差线,如链接中的示例所示。然而,这是特定于使用许多数据点的。在这种情况下,一个值被指定为错误,但错误不是从数据中确定的。
capsize可以指定该参数,在误差线的顶部和底部添加水平线。import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# set edgecolor param (this is a global setting, so only set it once)
plt.rcParams["patch.force_edgecolor"] = True
# setup the dataframe
Delay = ['S1', 'S2', 'S3', 'S4']
Time = [87, 66, 90, 55]
df = pd.DataFrame({'Delay':Delay,'Time':Time})
# create a dict for the errors
error = {87: {'max': 90,'min': 60}, 66: {'max': 70,'min': 40}, 90: {'max': 93,'min': 80}, 55: {'max': 60,'min': 23}}
Run Code Online (Sandbox Code Playgroud)
yerryerr期望值与条形顶部相关
S1是 87,min是 60,max是 90。 因此,ymin是 27, (87-60),ymax是 3, (90-87)。seaborn.barplot capsize参数似乎不适用于yerr,因此您必须设置matplotlib 'errorbar.capsize' rcParmas。请参阅Matplotlib 错误栏上限缺失# plot the figure
fig, ax = plt.subplots(figsize=(8, 6))
sns.barplot(x='Delay', y='Time', data=df, ax=ax)
# add the lines for the errors
for p in ax.patches:
x = p.get_x() # get the bottom left x corner of the bar
w = p.get_width() # get width of bar
h = p.get_height() # get height of bar
min_y = error[h]['min'] # use h to get min from dict z
max_y = error[h]['max'] # use h to get max from dict z
plt.vlines(x+w/2, min_y, max_y, color='k') # draw a vertical line
Run Code Online (Sandbox Code Playgroud)
pandas.DataFrame.plot.bar# set capsize param (this is a global setting, so only set it once)
plt.rcParams['errorbar.capsize'] = 10
# create dataframe as shown by gepcel
Delay = ['S1', 'S2', 'S3', 'S4']
Time = [87, 66, 90, 55]
_min = [60, 40, 80, 23]
_max = [90, 70, 93, 60]
df = pd.DataFrame({'Delay':Delay,'Time':Time, 'Min': _min, 'Max': _max})
# create ymin and ymax
df['ymin'] = df.Time - df.Min
df['ymax'] = df.Max - df.Time
# extract ymin and ymax into a (2, N) array as required by the yerr parameter
yerr = df[['ymin', 'ymax']].T.to_numpy()
# plot with error bars
fig, ax = plt.subplots(figsize=(8, 6))
sns.barplot(x='Delay', y='Time', data=df, yerr=yerr, ax=ax)
Run Code Online (Sandbox Code Playgroud)
ax.barfig, ax = plt.subplots(figsize=(8, 6))
df.plot.bar(x='Delay', y='Time', ax=ax)
for p in ax.patches:
x = p.get_x() # get the bottom left x corner of the bar
w = p.get_width() # get width of bar
h = p.get_height() # get height of bar
min_y = error[h]['min'] # use h to get min from dict z
max_y = error[h]['max'] # use h to get max from dict z
plt.vlines(x+w/2, min_y, max_y, color='k') # draw a vertical line
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16286 次 |
| 最近记录: |