首页 > 解决方案 > 使用 Pandas 创建图表

问题描述

我的代码在 Jupyter Notebook 中。

我可以使用下面的方法 1 创建一个图表,让它看起来和我想要的完全一样。

但是当我尝试使用 subplot 的方法 2 时,我不知道如何让它看起来一样(将 figsize、colors、legend 设置在右侧)。

如何使用 subplot,并让它看起来与方法 1 相同?

预先感谢您的帮助!

#  Using Numpy and Pandas

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.style as style

df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD'))

style.use('fivethirtyeight')

# Colorblind-friendly colors
colors = [[0,0,0], [230/255,159/255,0], [86/255,180/255,233/255], [0,158/255,115/255]]

# Method 1
chart = df.plot(figsize = (10,5), color = colors)
chart.yaxis.label.set_visible(True)
chart.set_ylabel("Bitcoin Price")
chart.set_xlabel("Time")
chart.legend(bbox_to_anchor=(1.05, 1), loc=2)
plt.show()

# Method 2
fig, ax = plt.subplots()
ax.plot(df)
ax.set_ylabel("Bitcoin Price")
ax.set_xlabel("Time")
plt.show()

标签: pythonpandas

解决方案


您只需将 char 替换为 ax,就像这样

ax.yaxis.label.set_visible(True) ax.set_ylabel("Bitcoin Price") ax.set_xlabel("Time") ax.legend(bbox_to_anchor=(1.05, 1), loc=2)


推荐阅读