pandas - 如何将元组绘制为 x 轴并绘制 y 轴上的列表
问题描述
假设我有以下形式的 df
import pandas as pd
import numpy as np
import matplotlib as plt
import matplotlib.pyplot as plt
col1
(0, 0, 0, 0) 1
(0, 0, 0, 2) 2
(0, 0, 2, 2) 3
(0, 2, 2, 2) 4
我想在 x 轴上绘制我的索引,在 y 轴上绘制 col1。
我试过的
plt.plot(list(df.index), df['col1'])
但是,它生成的情节不是我想要的。
解决方案
如果你给出一个 4 元组的列表x
for plt.plot()
,它们被解释为 4 个线图,一个包含元组中的第一个元素,一个包含第二个元素,等等。
您可以将元组转换为字符串以显示它们:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'y': [1, 2, 3, 4]}, index=[(0, 0, 0, 0), (0, 0, 0, 2), (0, 0, 2, 2), (0, 2, 2, 2)])
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 3))
ax1.plot(list(df.index), df['y'])
ax2.plot([str(i) for i in df.index], df['y'])
plt.show()
推荐阅读
- java - ArrayIndexOutOfBoundsException: 0 当我尝试访问将数据输入到数组的方法时
- disabled-control - 根据单元格值禁用选项按钮
- c# - 从 Scriptable Object 获取所有公共变量
- android - 按 ctrl+B 时找不到由 lombok 为类字段生成的 getter 声明(Android Studio 4.1.2)
- c++ - 努力从函数 C++ 中捕获返回值
- javascript - 反应购物车:我做错了什么
- variables - Websockets - 阻止在消息上分配的变量发生变化
- c++ - 从字符串指针数组中删除一个元素
- visual-studio-code - 如何在 Sublimetext 或 Visual Studio Code 中按名称查找文件夹?
- html - 试图弄清楚如何使我的 React 卡组件居中