给定以下代码:
import numpy as np
from matplotlib import pyplot as plt
from itertools import groupby
import pandas as pd
percent_EVs = [0, 8, 21, 26, 37, 39, 41, 75, 95, 97]
percent_DVs = [100, 92, 79, 74, 63, 61, 59, 25, 5, 3]
num_buses = [1423, 1489, 1613, 1606, 1710, 1684, 1694, 2153, 2202, 2195]
veh_range = ['DV only', 60, 120, 150, 60, 120, 150, 60, 120, 150]
deployment = ['DV only', 'Low', 'Medium', 'High', 'Low', 'Medium', 'High', 'Low', 'Medium', 'High']
df = pd.DataFrame({'Percent EVs': percent_EVs, 'Percent DVs': percent_DVs,
'# Buses': num_buses, 'Range (mi)':veh_range,
'Deployment target': deployment})
df.set_index('Range (mi)', inplace=True)
def add_line(ax, xpos, ypos):
line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
transform=ax.transAxes, color='black')
line.set_clip_on(False)
ax.add_line(line)
def label_len(my_index,level):
labels = my_index.get_level_values(level)
return [(k, sum(1 for i in g)) for k,g in groupby(labels)]
def label_group_bar_table(ax, df):
ypos = -.1
scale = 1./df.index.size
for level in range(df.index.nlevels)[::-1]:
pos = 0
for label, rpos in label_len(df.index,level):
lxpos = (pos + .5 * rpos)*scale
ax.text(lxpos, ypos, label, ha='center', transform=ax.transAxes)
add_line(ax, pos*scale, ypos)
pos += rpos
add_line(ax, pos*scale , ypos)
ypos -= .1
fig = plt.figure()
ax = fig.add_subplot(111)
#Your df.plot code with ax parameter here
df.plot.bar(stacked=True, rot=0, alpha=0.5, legend=False, ax=fig.gca())
labels = ['' for item in ax.get_xticklabels()]
ax.set_xticklabels(labels)
ax.set_xlabel('')
label_group_bar_table(ax, df)
fig.subplots_adjust(bottom=.2*df.index.nlevels, left=0.1*df.index.nlevels)
plt.show()
当前
结果图与所需的输出相差甚远。如何至少更改x轴标签以模拟所需的输出?
所需x轴
看这里,我试图创建以下图表:
1条答案
按热度按时间hm2xizp91#
以下是您正在寻找的解决方案: