首页 > 解决方案 > Matplotlib 的直方图图例为破折号

问题描述

出于好奇,有谁知道如何使直方图的图例类似于线图的图例?我正在计算 PDF,它更好地覆盖线。然而传说仍然是盒子

import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)

fig, ax = plt.subplots(figsize=(8, 8))

# Create scatter plot



ax.yaxis.set_major_locator(MultipleLocator(0.02))
ax.yaxis.set_major_formatter('{x:.2f}')
ax.yaxis.set_minor_locator(AutoMinorLocator(2))


ax.xaxis.set_major_locator(MultipleLocator(2))
ax.xaxis.set_major_formatter('{x:.0f}')
ax.xaxis.set_minor_locator(AutoMinorLocator(2))


ax.tick_params(which='minor', width=1, length=5, color='black')

ax.tick_params(which='major', width=1)

plt.xlim(0,22.0)
ax.hist(one, bins=15, density=True, stacked = True, lw=2, histtype='step',  label ='label')
.
.
.
.
ax.hist(four, bins=15, density=True, stacked = True, lw=2, histtype='step',  label ='label')
   

标签: pythonmatplotlib

解决方案


一种方法是在 x 轴上创建具有单个数据点的虚拟线图,仅用于使用它们的图例。请参见下面的示例:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('sample.csv')
fig, ax = plt.subplots(figsize=(8, 8))

ax.hist(df.col1, bins=4, density=True, stacked=True, lw=2, histtype='step', color = 'orange')
ax.hist(df.col2, bins=4, density=True, stacked=True, lw=2, histtype='step', color = 'cyan')

#dummy line plots:
ax.plot(2,0, label='first dataset', color = 'orange')
ax.plot(2,0, label='second dataset', color = 'cyan')

plt.legend()
plt.show()

在此处输入图像描述


推荐阅读