绘制文本框并填充Matplotlib Python中垂直线之间的颜色
based on another 线程我得到了此代码:
data = np.random.normal(loc=0.0, scale=1.0, size=2000)
df_data = pd.DataFrame(data)
import numpy as np
import scipy
import pandas as pd
from scipy.stats import norm
import matplotlib.pyplot as plt
def _plot(df):
for col in df.columns:
n_bins = 50
fig, axes = plt.subplots(figsize=(12,6))
n, bins, patches = axes.hist(df[col], n_bins, density=True, alpha=.1, edgecolor='black' )
mu = df[col].mean()
sigma = df[col].std()
pdf = 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(bins-mu)**2/(2*sigma**2))
#probability density function
axes.plot(bins, pdf, color='green', alpha=.6)
#dashed lines
plt.axvline(np.mean(df_data[0]),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]-sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]-2*sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]-3*sigma),color='b', linestyle='-.')
plt.axvline(min(df_data[0]),color='r', linestyle='-.')
plt.axvline(np.mean(df_data[0]+sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]+2*sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]+3*sigma),color='b', linestyle='-.')
plt.axvline(max(df_data[0]),color='r', linestyle='-.')
plt.ylabel('Probability Density')
plt.xlabel('Values')
print(mu)
print(sigma)
_plot(df_data)
您可以看到蓝色垂直线表示由标准偏差的倍数设置的边界。我想添加以下信息和颜色编码,现在我很快将其放置在PowerPoint:
“ https://i.sstatic.net/formj.png” alt =“在此处输入图像说明”>
我尝试与plt.fill_between
函数混乱有用。我也不知道如何写东西,例如Mu+l*Sigma,上面的 。我该如何根据自己的目标来实现第二张图片?
编辑: 由@Trenton McKinney
for i, (x, c) in enumerate(locs[:-1]):
axes.axvspan(x, locs[i + 1][0], alpha=0.2, color=c)
tx = (x + locs[i + 1][0]) / 2
axes.text(tx, y1/2, f'Zustand {i + 1}', {'ha': 'center', 'va': 'center'}, rotation=90)
if i<4:
axes.text(tx, y1/1.25, r"$\mu$" + "-" + f"{4-i}"+ "$\cdot$" + "$\sigma$" , {'ha': 'center', 'va': 'center'}, rotation=90, bbox=dict(facecolor='white', alpha=0.8, edgecolor='black'))
else:
axes.text(tx, y1/1.25, r"$\mu$" + "+" + f"{i-4 + 1}"+ "$\cdot$" + "$\sigma$" , {'ha': 'center', 'va': 'center'}, rotation=90, bbox=dict(facecolor='white', alpha=0.8, edgecolor='black'))
based on another thread i got this code:
data = np.random.normal(loc=0.0, scale=1.0, size=2000)
df_data = pd.DataFrame(data)
import numpy as np
import scipy
import pandas as pd
from scipy.stats import norm
import matplotlib.pyplot as plt
def _plot(df):
for col in df.columns:
n_bins = 50
fig, axes = plt.subplots(figsize=(12,6))
n, bins, patches = axes.hist(df[col], n_bins, density=True, alpha=.1, edgecolor='black' )
mu = df[col].mean()
sigma = df[col].std()
pdf = 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(bins-mu)**2/(2*sigma**2))
#probability density function
axes.plot(bins, pdf, color='green', alpha=.6)
#dashed lines
plt.axvline(np.mean(df_data[0]),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]-sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]-2*sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]-3*sigma),color='b', linestyle='-.')
plt.axvline(min(df_data[0]),color='r', linestyle='-.')
plt.axvline(np.mean(df_data[0]+sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]+2*sigma),color='b', linestyle='-.')
plt.axvline(np.mean(df_data[0]+3*sigma),color='b', linestyle='-.')
plt.axvline(max(df_data[0]),color='r', linestyle='-.')
plt.ylabel('Probability Density')
plt.xlabel('Values')
print(mu)
print(sigma)
_plot(df_data)
Which returns me this nice plot:
As you can see the blue vertical lines indicate borders set by multiples of standard deviations. I would like to add the following information and color coding, which I now quickly placed in powerpoint:
I tried to mess with the plt.fill_between
function but didnt really get anything useful. Also I do not know how to write something, like the mu+l*sigma here, above the plot. How can i achieve the second picture based on what I have?
EDIT:
solved by @Trenton McKinney
Putting new boxes inside the colored boxes:
for i, (x, c) in enumerate(locs[:-1]):
axes.axvspan(x, locs[i + 1][0], alpha=0.2, color=c)
tx = (x + locs[i + 1][0]) / 2
axes.text(tx, y1/2, f'Zustand {i + 1}', {'ha': 'center', 'va': 'center'}, rotation=90)
if i<4:
axes.text(tx, y1/1.25, r"$\muquot; + "-" + f"{4-i}"+ "$\cdotquot; + "$\sigmaquot; , {'ha': 'center', 'va': 'center'}, rotation=90, bbox=dict(facecolor='white', alpha=0.8, edgecolor='black'))
else:
axes.text(tx, y1/1.25, r"$\muquot; + "+" + f"{i-4 + 1}"+ "$\cdotquot; + "$\sigmaquot; , {'ha': 'center', 'va': 'center'}, rotation=90, bbox=dict(facecolor='white', alpha=0.8, edgecolor='black'))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
axvspan
andtext
text 放置。在这种情况下,使用词典。更新其他注释
< img src =“ https://i.sstatic.net/bsx2m.png” alt =“在此处输入图像说明”>
axvspan
andtext
placement. In this case, a dictionary is used..Axes.axvspan
to fill between vertical positions.Axes.text
python 3.10
,matplotlib 3.5.1
Update for additional annotations