首页 > 解决方案 > 如何将元组绘制为 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']) 

但是,它生成的情节不是我想要的。

标签: pandasmatplotlib

解决方案


如果你给出一个 4 元组的列表xfor 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()

元组的线图


推荐阅读