python - 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')
解决方案
一种方法是在 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()
推荐阅读
- javascript - 访问对象需要setTimeout?
- javascript - 如何从 upbit.com 网站提取数据
- numpy - 由于 numpy 问题,无法从控制台启动 tensorboard
- javascript - 如何从循环中将多个 Json 对象添加到单个数组
- python - 列内的模糊匹配
- c - 接收自己发送的消息的原始套接字
- php - 在 codeigniter 中更改选择不同语言的 url
- wordpress - Wordpress WooCommerce 菜单扩展大搜索按钮删除
- java - 以编程方式在 JpaProperties - Spring 中添加休眠拦截器
- python - 计算在 python 中实现的隔离森林的异常分数