python绘制累积柱状图

改变Matplotlib图例中项目的顺序

df_group_height.plot.bar(x='season', y=df_group_height.columns[1:].values, stacked=True)
ax = plt.gca()  # get cart axes 的缩写
ax.set_xticklabels(df_group_height['season'], rotation=90, ha='right')
plt.tight_layout()
# get handles and labels
handles, labels = plt.gca().get_legend_handles_labels()
# specify order of items in legend
order = [i for i in range(len(df_group_height.columns[1:].values))][::-1]
# add legend to plot
plt.legend([handles[idx] for idx in order], [labels[idx] for idx in order])

# reorderLegend(ax, [50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 160, 180])
plt.show()

链接1

添加标签

import numpy as np
import matplotlib.pyplot as plt

category_names = ['Strongly disagree', 'Disagree', 'Neither agree nor disagree', 'Agree', 'Strongly agree']
results = {
    
    
    'Question 1': [10, 15, 17, 32, 26],
    'Question 2': [26, 22, 29, 10, 13],
    'Question 3': [35, 37, 7, 2, 19],
    'Question 4': [32, 11, 9, 15, 33],
    'Question 5': [21, 29, 5, 5, 40],
    'Question 6': [8, 19, 5, 30, 38]
    }
def survey(results, category_names):
    labels = list(results.keys())
    # 获取标签
    data = np.array(list(results.values()))
    # 获取具体数值
    data_cum = data.cumsum(axis=1)
    # 逐项加和
    category_colors = plt.get_cmap('RdYlGn')(np.linspace(0.15, 0.85, data.shape[1]))

    """
    在cmmap中取出五组颜色
    category_colors:
        [[0.89888504 0.30549789 0.20676663 1.        ]
         [0.99315648 0.73233372 0.42237601 1.        ]
         [0.99707805 0.9987697  0.74502115 1.        ]
         [0.70196078 0.87297193 0.44867359 1.        ]
         [0.24805844 0.66720492 0.3502499  1.        ]]

    """

    print(category_colors)
    # 常见颜色序列, 在cmap中取色

    fig, ax = plt.subplots(figsize=(5, 9))
    # 绘图
    # ax.invert_xaxis()
    # 使其更符合视觉习惯,index本身从下到上
    ax.yaxis.set_visible(False)
    ax.set_xticklabels(labels=labels, rotation=90)
    # 不需要可见
    ax.set_ylim(0, np.sum(data, axis=1).max())

    for i, (colname, color) in enumerate(zip(category_names, category_colors)):
        heights = data[:, i]
        # 取第一列数值
        starts = data_cum[:, i] - heights
        # 取每段的起始点
        ax.bar(labels, heights, bottom=starts, width=0.5,
               label=colname, color=color)
        xcenters = starts + heights / 2
        r, g, b, _ = color
        text_color = 'white' if r * g * b < 0.5 else 'darkgrey'
        for y, (x, c) in enumerate(zip(xcenters, heights)):
            ax.text(y, x, str(int(c)), ha='center', va='center',
                    color=text_color, rotation=90)
    ax.legend()
    return fig, ax

survey(results, category_names)
plt.show()

在这里插入图片描述
案例2

Python中如何使用matplotlib给柱状图添加数据标签(bar_label())
https://blog.csdn.net/qq_32117641/article/details/104116306;

修改图例大小

plt.legend(prop={
    
    'family':'SimHei','size':4})

案例

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none", cmap="plasma")

divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("left", "15 %", pad="30 %")

plt.colorbar(im, cax=cax)

fig.suptitle('matplotlib.pyplot.gca() function Example\n\n', fontweight="bold")
plt.show()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46713695/article/details/130325596
今日推荐