如何在 python 中绘制多个 pandas 数据框时设置图例和其他属性?
How to set a legend and other attributes while plotting several pandas data frames in python?
我有一个数据框列表,我想以两种方式在同一张图中绘制这些数据框。我从一个难以理解的简单线图和一个同样令人困惑的散点图开始。我的想法是将两者结合起来以查看数据点并将它们连接起来,如下所示:
Both scatter and lineplot
在此处使用此代码绘制:
#set common Coordinate System
ax = plt.gca()
#create apropriate colour map
#set how many levels of shades are allowed
shade_level = len(zreal_zimg_dfs) * 100 + 1
shades = np.arange(shade_level)
#create Normalize object for mappable (necessary)
norm = mpl.colors.Normalize(vmin=shades.min(), vmax=shades.max())
#create colourmap that creates all levels of shade of a certain colour
shades = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Blues)
# x determines what shade of the colour to be used last (in percent; e.g. 0.15 == 15% colour)
x = 0.25
#'colourstep' to take to be equally 'spaced'
shade_step = int(shade_level * (1-x) / len(zreal_zimg_dfs))
#plot, set label, marker and linesizes and colours
for i in range(len(zreal_zimg_dfs)):
#plot the markerpoints (scatter)
zreal_zimg_dfs[i].plot( x = 'Zreal1', y = 'Zimg1', ax = ax, label = '{nr}. {date}'.format(nr = i+1, date = dates[i]),
xlabel = 'Z-Realteil (mOhm)', ylabel = 'Z-Imaginärteil (mOhm)',
color = shades.to_rgba(max(shade_level - i * shade_step, shade_level * x)),
kind = 'scatter', marker = '.', s = 8)
zreal_zimg_dfs[i].plot( x = 'Zreal1', y = 'Zimg1', ax = ax,
color = shades.to_rgba(max(shade_level - i * shade_step, shade_level * x)),
linewidth = 0.2, legend = False)
#ax.legend(loc = 'upper right', frameon = False)
plt.title('Impedanz NMC{nmc_nr} Test EIS{EIS_nr}'.format(nmc_nr = nmc_nr, EIS_nr = EIS_nr))
plt.savefig('Impedanz NMC{nmc_nr} Test EIS{EIS_nr}.png'.format(nmc_nr = nmc_nr, EIS_nr = EIS_nr), dpi = 600)
plt.show()
此代码的大部分内容都涉及创建颜色图,所以请不要混淆。当我尝试调整情节的图例时,我的问题就出现了。注意评论
ax.legend(loc = 'upper right', frameon = False)
取消注释后,图例就完全乱了。我也用 plt.legend 试过这个,但得到了同样混乱的结果:
Legend messed up
我不确定这里的问题是什么,但老实说,我很难理解 pandas plot 和常规 matplotlib 如何交互以及 fig、ax 和 plt 之间的确切区别。非常感谢任何帮助。
使用 Pandas 绘制绘图时,某些 Matplotlib 功能很奇怪。有时使用 Matplotlib OOP 风格会更好。当您放置 ax.legend()
时,将重新制作图例,无论您将 legend=False
放置在线条图中。对于这种情况,我建议您获取图例的处理程序,然后 select 只获取您需要的。这是一个例子:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(10, 5), columns=['col0', 'col1', 'col2', 'col3', 'col4'])
ax = plt.gca()
for i in range(1, 5):
df.plot(x='col0', y=f'col{i}', kind = 'scatter', marker = '.', s = 20, ax=ax, color=f'C{i}', label=f'scater {i}')
df.plot(x='col0', y=f'col{i}', linewidth = 1, legend = False, ax=ax, color=f'C{i}')
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[4:], labels[4:], loc ='upper left', frameon = False, bbox_to_anchor=(1, 0.5))
我有一个数据框列表,我想以两种方式在同一张图中绘制这些数据框。我从一个难以理解的简单线图和一个同样令人困惑的散点图开始。我的想法是将两者结合起来以查看数据点并将它们连接起来,如下所示: Both scatter and lineplot
在此处使用此代码绘制:
#set common Coordinate System
ax = plt.gca()
#create apropriate colour map
#set how many levels of shades are allowed
shade_level = len(zreal_zimg_dfs) * 100 + 1
shades = np.arange(shade_level)
#create Normalize object for mappable (necessary)
norm = mpl.colors.Normalize(vmin=shades.min(), vmax=shades.max())
#create colourmap that creates all levels of shade of a certain colour
shades = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Blues)
# x determines what shade of the colour to be used last (in percent; e.g. 0.15 == 15% colour)
x = 0.25
#'colourstep' to take to be equally 'spaced'
shade_step = int(shade_level * (1-x) / len(zreal_zimg_dfs))
#plot, set label, marker and linesizes and colours
for i in range(len(zreal_zimg_dfs)):
#plot the markerpoints (scatter)
zreal_zimg_dfs[i].plot( x = 'Zreal1', y = 'Zimg1', ax = ax, label = '{nr}. {date}'.format(nr = i+1, date = dates[i]),
xlabel = 'Z-Realteil (mOhm)', ylabel = 'Z-Imaginärteil (mOhm)',
color = shades.to_rgba(max(shade_level - i * shade_step, shade_level * x)),
kind = 'scatter', marker = '.', s = 8)
zreal_zimg_dfs[i].plot( x = 'Zreal1', y = 'Zimg1', ax = ax,
color = shades.to_rgba(max(shade_level - i * shade_step, shade_level * x)),
linewidth = 0.2, legend = False)
#ax.legend(loc = 'upper right', frameon = False)
plt.title('Impedanz NMC{nmc_nr} Test EIS{EIS_nr}'.format(nmc_nr = nmc_nr, EIS_nr = EIS_nr))
plt.savefig('Impedanz NMC{nmc_nr} Test EIS{EIS_nr}.png'.format(nmc_nr = nmc_nr, EIS_nr = EIS_nr), dpi = 600)
plt.show()
此代码的大部分内容都涉及创建颜色图,所以请不要混淆。当我尝试调整情节的图例时,我的问题就出现了。注意评论
ax.legend(loc = 'upper right', frameon = False)
取消注释后,图例就完全乱了。我也用 plt.legend 试过这个,但得到了同样混乱的结果:
Legend messed up
我不确定这里的问题是什么,但老实说,我很难理解 pandas plot 和常规 matplotlib 如何交互以及 fig、ax 和 plt 之间的确切区别。非常感谢任何帮助。
使用 Pandas 绘制绘图时,某些 Matplotlib 功能很奇怪。有时使用 Matplotlib OOP 风格会更好。当您放置 ax.legend()
时,将重新制作图例,无论您将 legend=False
放置在线条图中。对于这种情况,我建议您获取图例的处理程序,然后 select 只获取您需要的。这是一个例子:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(10, 5), columns=['col0', 'col1', 'col2', 'col3', 'col4'])
ax = plt.gca()
for i in range(1, 5):
df.plot(x='col0', y=f'col{i}', kind = 'scatter', marker = '.', s = 20, ax=ax, color=f'C{i}', label=f'scater {i}')
df.plot(x='col0', y=f'col{i}', linewidth = 1, legend = False, ax=ax, color=f'C{i}')
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[4:], labels[4:], loc ='upper left', frameon = False, bbox_to_anchor=(1, 0.5))