python - 如何注释下图?
问题描述
我使用 3 个不同的熊猫系列制作了直方图。我想标记条形组 1、2 和 3。我没有成功使用 xlabels 来执行此操作;从技术上讲,它可以工作,但数字 1、2、3 没有与条正确对齐。
我决定跳过它并尝试注释。不幸的是,我知道如何正确地做到这一点。
我尝试使用 xlabels,但未成功。现在我正在尝试注释,但我无法在图表上显示多个文本。
以下是数据的示例 Wr_Spr_Conv = [1,1,1,2,2,2,3,3,3,2,2,1,2,3...]
new2['Wr_Spr_Conv'].replace(0, pd.np.nan).dropna(inplace = True)
new2['Re_Spr_Conv'].replace(0, pd.np.nan).dropna(inplace = True)
new2['Ma_Spr_Conv'].replace(0, pd.np.nan).dropna(inplace = True)
plt.style.use('seaborn')
x_labels = [1,2,3]
fig, ax1 = plt.subplots(figsize=(10,10))
#ax1.spines['left'].set_position(('outward', 10))
#ax1.spines['bottom'].set_position(('outward', 10))
# Hide the right and top spines
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.spines['right'].set_visible(False)
nbins = 9
ax1.tick_params(bottom="off", top="off", left="off", right="off")
ax1.hist([new2['Wr_Spr_Conv'],new2['Re_Spr_Conv'],new2['Ma_Spr_Conv']],nbins)
#ax1.set_xticks(3)
#ax1.set_xticks(3)
#ax1.set_xlim(right =3)
#ax1.set_xlim(left=0)
# Only show ticks on the left and bottom spines
#ax1.yaxis.set_ticks_position('left')
#ax1.xaxis.set_ticks_position('bottom')
ax1.set_xticks(x_labels)
ax1.set_xlim(right=3) # adjust the right leaving left unchanged
ax1.set_xlim(left=1) # adjust the left leaving right unchanged
ax1.xaxis.set_major_locator(MaxNLocator(integer=True))
#ax1.annotate('Level 1',xy=(1,15))
解决方案
假设你Wr_Spr_Conv
是pandas.Series,你可以使用value_counts
pyplot 的bar
方法和属性align='center'
来创建一个带有预定义数量的 bin 和 centered labels的直方图。
这是一个最小的例子:
import pandas as pd
from matplotlib import pyplot as plt
nbr_bins = 9
Wr_Spr_Conv = pd.Series( [1,1,1,2,2,5,9,2,7,7,2,3,3,3,2,2,1,2,3])
vc = Wr_Spr_Conv.value_counts(bins=nbr_bins)
plt.bar(vc.index.mid, vc.values, width=0.9*vc.index.length[0], align='center')
plt.gca().set_xticks(vc.index.mid)
plt.show()
这应该让你开始!
推荐阅读
- java - java.nio.buffer.flip() 什么时候可以抛出 NullPointerException?
- sql - SQLite 选择查询优化
- dart - Angular Dart 的调试在 PhpStorm 中停止工作
- vue.js - 如何更新 vue2-frappe 图表?
- python - 获取特定行的内容
- r - 在 r 中加载我训练有素的 keras 模型时出现致命错误
- reactjs - 我可以使用原生 react js 开发 chrome 扩展吗?
- git - Git历史既重写又不变?
- elasticsearch - 使用 wordnet 的 Elasticsearch 同义词搜索不起作用
- x86-16 - 可编程中断控制器(PIC)使用主从协议最多可以保存 64 个中断向量。其他的呢?