python - matplotlib:如何绘制 3d 直方图
问题描述
我有一个如下所示的数据框:
date shop success
1 12/06/2020 A 0.99
2 15/06/2020 A 0.95
3 17/07/2020 B 0.94
4 22/07/2020 B 0.97
...
我想绘制一个类似于这种类型的 3d 直方图:
这三个维度将是:
- x:日期
- y:商店
- z:成功
我浏览了许多网站,但无法找到一种方法。我对编程很陌生。
谢谢你的帮助!!
解决方案
简短回答:可以完成,但您必须修改 DataFrame 结构。
长答案:
必要的库:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
数据框中的“日期”和“商店”列不是数值。这意味着,您必须在没有它们的情况下构建图形,然后使用它们来标记轴上的刻度。因此,让我们先压缩空图。这是您需要的数据框结构。
df = pd.DataFrame({"A": [0.0, 0.0, 0.0, 0.0],"B": [0.0, 0.0, 0.0, 0.0]})
您需要按“商店”对所有值进行分组,并使用“商店”作为主要变量!
# Setting length and wight of the bars
dx, dy = .9, .01
# prepare 3d axes
fig = plt.figure(figsize=(6,6))
ax = Axes3D(fig)
# set bar positions on axes
xpos=np.arange(df.shape[0])
ypos=np.arange(df.shape[1])
# set the ticks in the middle of the bars
ax.set_xticks(xpos + dx/2)
ax.set_yticks(ypos + dy/2)
# create X, Y grid
xpos, ypos = np.meshgrid(xpos, ypos)
xpos = xpos.flatten()
ypos = ypos.flatten()
# set the start of the bar to 0
zpos=np.zeros(df.shape).flatten()
# the bar heights these are the values under the column A and B
dz = df.values.ravel()
# ploting the barchart
ax.bar3d(xpos,ypos,zpos,dx,dy,dz)
# Labeling the ticks. For simplicity's sake I used lists for labeling but you can also iterate through columns "Date" and "Shop" to get the label values
ax.w_yaxis.set_ticklabels(["A", "B"])
ax.w_xaxis.set_ticklabels(["12/06/2020", "15/06/2020", "17/07/2020", "22/07/2020" ])
# Label the axes
ax.set_xlabel("Date")
ax.set_ylabel("Shop")
ax.set_zlabel("Success")
plt.show()
输出:
完美的!如您所见,我们的基地在一个轴上设有商店 A 和 B,在另一轴上设有日期。现在我们可以在原始 DataFrame 中输入一些数据并定义“Success”Z 值。
df = pd.DataFrame({"a": [0.1, 0.2, 0.3, 0.4],"b": [0.2, 0.3, 0.4, 0.5]})
您拥有的商店越多,您拥有的斧头就越多……
df = pd.DataFrame({"a": [0.1, 0.2, 0.3, 0.4],"b": [0.2, 0.3, 0.4, 0.5], "c": [0.1, 0.4, 0, 1.4]})
您可以使用“alpha=”和“color=”等传统参数设置条形样式,但请记住,您有多个列,因此您必须为每个参数提供列表,而不是单个值。
干杯:)
推荐阅读
- python - 如何使用 scipy 解决数组的非线性系统
- json - 是否可以在一行中更新 NamedTuple?
- c++ - 基于 i.MX6 和 MT41K256M16TW-107 IT:P 的定制硬件设计的意外行为
- java - 使用 Visual Studio Code 将 Java Web 应用程序部署到 Tomcat
- spring - org.springframework.cloud.task.launcher.TaskLauncherSink 需要一个 'org.springframework.cloud.deployer.spi.task.TaskLauncher' 类型的 bean
- c++ - 使用 boost::regex 从目录中获取带有一些正则表达式的文件名时出现意外输出
- javascript - 如何在 Mobx-State-Tree 中有一个可为空的字符串值
- python - pip install myclient 错误 - 在 Windows 7 上使用 Python 3.7.0
- spring-mvc - 从 WebFlux 中的 WebFilter 获取 HandlerMethod
- wpf - 组合框触摸事件未在 Windows 10 VS2017 中触发