python - 如何根据 matplotlib 中的单元格字符串以彩色网格方式绘制时间序列?
问题描述
我正在尝试 在 matplotlib中生成像这样的图
基于这样构造的 pandas 数据框:
2020-01-01 2020-01-02 2020-01-03 ...
X yellow red red ...
Y orange orange red ...
Z red yellow yellow ...
... ... ... ... ...
我认为这可能是用 2D 直方图完成的,但没有运气。我已经看到这pcolor
可能是我正在寻找的功能,但我无法管理它与我的时间系列数据框一起工作。
解决方案
你可以用seaborn
. 您需要用数字替换颜色,因此您将拥有这样的数据框:
你可以sns.heatmap
用来绘制:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
data = {'date': pd.date_range("2020-01-01", "2020-01-31", freq="1D").strftime('%d %b'),
'a': np.random.randint(3, size=31), 'b': np.random.randint(3, size=31),
'c': np.random.randint(3, size=31), 'd': np.random.randint(3, size=31),
'e': np.random.randint(3, size=31), 'f': np.random.randint(3, size=31)}
df = pd.DataFrame.from_dict(data)
df = df.set_index('date')
df = df.transpose()
fig, ax = plt.subplots(figsize=[10,2])
ax = sns.heatmap(df, cmap=['yellow', 'orange', 'red'], cbar=False)
如果您愿意matplotlib
,可以使用imshow
:
from matplotlib.colors import ListedColormap
fig, ax = plt.subplots(figsize=[10,2])
ax.set_xticks(np.arange(len(df.columns)))
ax.set_yticks(np.arange(len(df.index)))
ax.set_xticklabels(df.columns)
ax.set_yticklabels(df.index)
plt.setp(ax.get_xticklabels(), rotation=90)
ax.imshow(df, ListedColormap(['yellow', 'orange', 'red']))
推荐阅读
- node.js - 在 Sequelize 查找方法的条件中使用列别名时出错
- python - 不知道服务器 IP 时如何使用 Python SMB 连接?
- python - OpenCV:增强视频流源 .png 未按预期呈现透明度
- wso2 - 在 WSO2 流处理器中启动 Siddhi 应用程序时出错:javax/jms/JMSContext
- php - 如何将内容附加到php文件中的数组
- python-3.x - 使用字典中的两个对象创建一个嵌套对象
- r - R 语法中的替换/占位符变量
- java - 在 JDeveloper 中,如何指定要使用哪个类的“主”?
- android - 如何将 ImageView 高度与其父级 wrap_content 匹配?(回收站查看项目)
- python - 如何在python中执行shell命令文件