python - 我该怎么做才能使这个 matplotlib .bar 贡献图表代码在 python 中工作?
问题描述
我正在尝试绘制财务贡献分析,一个带有两个垂直条的条形图,一个代表股票贡献的投资组合收益,另一个代表Fixed Income (bonds)
特定时间段内的投资组合收益。
%matplotlib inline
import numpy as np
import pandas as pd
import itertools
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.lines as mlines
import matplotlib.dates as mdates
import matplotlib.font_manager as fm
import matplotlib.patches as mpatches
import matplotlib.transforms as mtrans
d = {'col1': [0.006269, 0.003842, 0.002237, 0.001448, 0.000752, 0.000166]}
equity = pd.DataFrame(data=d, index=['Aktien Nordamerika', 'Gold', 'Aktien Flexibel', 'Aktien Europa', 'Aktien Schwellenlaender', 'Aktien Pazifik'])
d2 = {'col1': [0.009533, 0.003879, 0.001926, 0.000714]}
bonds = pd.DataFrame(data=d2, index=['Anleihen Investmentgrade', 'Hedgefonds', 'Hochzinsanleihen', 'Anleihen Schwellenlaender'])
从 x 轴开始的垂直条总和应代表总增益,['equity','bonds‘]
但除以 df 中定义的索引。
我试图通过使用迭代器构建块itertools.zip_longest
来分配递增条形图的值,然后分配每个部分的颜色。
fig, ax = plt.subplots()
fig.set_size_inches(4, 4.3)
bar_width = 0.26
x_values = np.array([0, 1.2])
x_pos = [list(x_values)]*2 + [x_values[0]]*4
pl = [(p1,p2) if p2 is not None else p1 for p1, p2 in itertools.zip_longest(list(equity['col1'].values), list(bonds['col1'].values))]
colors = np.array((
['#FF7600', '#A9A9A9', '#1778A6', '#146189', '#5794B9', '#B0D2E7'],
['#004232', '#3AC2A0', '#007558', '#2A8C74']))
colormap = [(c1,c2) if c2 is not None else c1 for c1, c2 in itertools.zip_longest(colors[0],colors[1])]
那么我将只使用 matplotlibmatplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
来创建所需的条形图..
for x, p, c in zip(x_pos, pl, colormap):
ls_sub_aktien = plt.bar(x, p, align='edge', width=bar_width, linewidth=0.0001, color=c)
但是输出并没有给我在['bonds']
栏中的总划分,其中只有两个行项按定义着色......
此外,左侧栏似乎包含一种实际上应该在右侧栏中找到的颜色。
如果您遇到过类似的问题并记得您是如何解决它的,或者您对我如何使用不同的方法创建此图表有建议,那将是非常棒的。对不起我的英语,如果有任何不清楚的地方请告诉我。请尝试一下。想知道能不能解决,谢谢!
解决方案
推荐阅读
- kendo-ui - 传递列表
到 ASP MVC 中的剑道网格 - macos - 在 sed 中插入标签
- android - 如何强制 manifest.json 在现有 Android 设备上刷新
- ruby-on-rails - Ruby:哈希:使用一个记录属性作为键,另一个作为值
- angularjs - 如何使用基于表格行的自定义消息验证 angularjs 中的空字段
- c# - .net 4.5 控制器:参数多态性和自定义 Json 反序列化
- c++ - 当我按值传递参数时对象被破坏?
- amazon-web-services - 如何防止从云端重定向到我的服务器?
- r - 如何使用吉布斯采样计算 LDA 的困惑度
- javascript - Promise.all 在移动到 .then 之前不等待承诺完成