图例中仅显示一个数据名

时间:2019-01-23 17:19:28

标签: python pandas matplotlib

我喜欢显示两个数据列的图表。问题在于图例仅显示姓氏l/s

这是我的图:

Diagram

import pandas as pd
import matplotlib.pyplot as plt

Tab = pd.read_csv('Mst01.csv', delimiter=';')

x =  Tab['Nr. ']
y1 = Tab['cm']
y2 = Tab['l/s']

fig, ax1 = plt.subplots()

 ax2 = ax1.twinx()
 ax1.plot(x, y1, 'g-', label='cm')
 ax2.plot(x, y2, 'b-', label='l/s')

 ax1.set_xlabel('Nr.')
ax1.set_ylabel('cm', color='g')

ax2.set_ylabel('l/s', color='b')


plt.title('Mst01')

 plt.legend()

 plt.show()

如果我愿意      ax1.legend()      ax2.legend()

两个图例都会显示,但一个在另一个之上。

顺便问一下,有没有一种更简单的方法来获取每一行代码的空格?

1 个答案:

答案 0 :(得分:0)

晚上好!

所以您有两种可能性,要么将图加在一起,要么使用fig.legend()

这是产生解决方案的一些示例代码

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

# Create Example Dataframe
dummy_data = np.random.random_sample((100,2))
df = pd.DataFrame(dummy_data, columns=['Col_1', 'Col_2'])
df.Col_2 = df.Col_2*100

# Create Figure
fig, ax = plt.subplots()

col_1 = ax.plot(df.Col_1, label='Col_1', color='green')
ax_2 = ax.twinx()
col_2 = ax_2.plot(df.Col_2, label='Col_2', color='r')

# first solution
lns = col_1+col_2
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc='upper right')

# secound solution
fig.legend()
fig

解决方案可以从此question中得出。

空格是什么意思?你的意思是缩进for循环?