图例中仅显示一个数据名 [英] Only one dataname shows in the legend

查看:78
本文介绍了图例中仅显示一个数据名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢显示两个数据列的图表.关于它的问题是图例只显示姓氏l/s.

I like to display a diagram of two data columns. The problem about it is that the legend shows only the last name l/s.

这是我的图表:

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()

If I do ax1.legend() ax2.legend()

两个图例都将显示,但一个在另一个之上.

both legends will displayed but one above the other.

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

By the way, is there a easyier way the get the spaces for every line of code?

推荐答案

晚上好!

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

so you got two possibilities either you add the plots together or you use fig.legend()

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

here is some sample code which yields to the solution

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

解决方案可以从以下问题.

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

What do you mean by spaces? you mean the indention of e.g. a for loop?

这篇关于图例中仅显示一个数据名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆