这是我第一次尝试在参加卫斯理的Wesley教程后玩熊猫图书馆。在熊猫数据框上绘制堆叠的条形图
经过对数据框的讨论后,我很高兴能够以我想要的方式按摩数据,但在绘制时遇到麻烦。我想这也指向了我对matplotlib库的天真。
我所拥有的是具有以下数据的熊猫系列对象。我想绘制为col 1('文件')作为垂直方向标签的barplot。
样本数据在这里: http://pastebin.com/y2w0uJPQ
这是我第一次尝试在参加卫斯理的Wesley教程后玩熊猫图书馆。在熊猫数据框上绘制堆叠的条形图
经过对数据框的讨论后,我很高兴能够以我想要的方式按摩数据,但在绘制时遇到麻烦。我想这也指向了我对matplotlib库的天真。
我所拥有的是具有以下数据的熊猫系列对象。我想绘制为col 1('文件')作为垂直方向标签的barplot。
样本数据在这里: http://pastebin.com/y2w0uJPQ
我刚刚实施了大熊猫Git仓库堆叠柱状图功能,将是即将到来的0.7.3版本的一部分:
In [7]: df
Out[7]:
a b c
0 0.425199 0.564161 0.727342
1 0.174849 0.071170 0.679178
2 0.224619 0.331846 0.468959
3 0.654766 0.189413 0.868011
4 0.617331 0.715088 0.387540
5 0.444001 0.069016 0.417990
6 0.203908 0.689652 0.227135
7 0.382930 0.874078 0.571042
8 0.658687 0.493955 0.245392
9 0.758986 0.385871 0.455357
In [8]: df.plot(kind='barh', stacked=True)
它妥善处理正面和负面的(在原点和正值之上叠加负值)
哇!看起来我在找什么!你如何做垂直? – moldovean 2014-04-14 14:26:58
最近我编程的功能做一些非常相似。在这里你有一个简化版本:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.colors import colorConverter
import matplotlib.lines as mlines
import matplotlib
def _add_legend(axes):
'It adds the legend to the plot'
box = axes.get_position()
axes.set_position([box.x0, box.y0, box.width * 0.9, box.height])
handles, labels = axes.get_legend_handles_labels()
# sort by the labels
handel_lables = sorted(zip(handles, labels), key=operator.itemgetter(1))
handles, labels = zip(*handel_lables)
axes.legend(handles, labels, bbox_to_anchor=(1.05, 1), loc=2,
borderaxespad=0., prop={'size':LEGEND_FONT_SIZE},
fancybox=True, numpoints=1)
def stacked_bars(matrix, fhand, bar_colors=None):
'It draws stacked columns'
bar_width = 1
fig = Figure(figsize=FIGURE_SIZE)
canvas = FigureCanvas(fig)
axes = fig.add_subplot(111)
nrows, ncols = matrix.shape
bar_locs = range(0, nrows)
cum_heights = numpy.zeros(nrows)
for col_index, (col_name, column) in enumerate(matrix.iteritems()):
color = bar_colors[col_index] if bar_colors is not None else None
values = column.values
axes.bar(bar_locs, values, color=color, bottom=cum_heights,
width=bar_width, label=col_name)
cum_heights += values
min_y, max_y = axes.get_ylim()
#bar labels
axes.set_xticks([l + bar_width * 0.4 for l in bar_locs])
labels = axes.set_xticklabels([str(l) + ' ' for l in matrix.index.values],
fontsize=AXIS_LABELS_FONT_SIZE)
for label in labels:
label.set_rotation('vertical')
_add_legend(axes)
canvas.print_figure(fhand, format=_get_format_from_fname(fhand.name))
fhand.flush()
我希望它可以帮助你得到一个想法。
我认为这个函数只处理正值(在计算累积高度时需要分开正值和负值) – 2012-04-08 16:34:46
你说得对,我只关心正值,因为在我的情况下负值不被允许。 – 2012-04-10 09:01:24
我假设你想要比'myserie.plot(kind ='bar')'更多的东西吗? – Avaris 2012-03-30 07:03:41