【问题标题】:Adding information to a legend with Matplotlib使用 Matplotlib 向图例添加信息
【发布时间】:2014-08-08 16:41:48
【问题描述】:

我有一组应用程序上行链路/下行链路的图,分布用 CDF 显示,我想通过在图例中添加更多信息来改进图,例如,我希望它显示数字每个变量的点, 对于这段代码,而不是向我展示:

--- Uplink
___ Downlink

我想看看这个:

--- Uplink(54)
___ Downlink(88)

其中 54 是此上行链路中的绘制点数,其中 88 是此下行链路中的绘制点数

这是我想要改进的代码:

import csv
import matplotlib.pyplot as plt
import pylab
#---Reading from a csv file
def getColumn(filename, column):
    results = csv.reader(open(filename), delimiter="\t")
    return [result[column] for result in results]
#---the cdf Function
def cdf(inputList):
    outputList = []
    inputList.sort()
    for i in range(0, len(inputList)):
        outputList.append( [inputList[i], (i+1.0)/len(inputList)] )
    return outputList
#--getting the data i want from the csv file
fgfS=getColumn("dataFG.csv",2)
bgfS=getColumn("dataBG.csv",2)
fgifS=getColumn("dataiFG.csv",2)
bgifS=getColumn("dataiBG.csv",2)
#---the points to plot:
fgfS1=[]
fgfS2=[]

for i in cdf(map(float,fgfS)):
    fgfS1.append(i[0])
    fgfS2.append(i[1])

bgfS1=[]
bgfS2=[]
for i in cdf(map(float,bgfS)):
    bgfS1.append(i[0])
    bgfS2.append(i[1])

fgifS1=[]
fgifS2=[]

for i in cdf(map(float,fgifS)):
    fgifS1.append(i[0])
    fgifS2.append(i[1])

bgifS1=[]
bgifS2=[]
for i in cdf(map(float,bgifS)):
    bgifS1.append(i[0])
    bgifS2.append(i[1])


fig2, (ax2,ax02) = plt.subplots(1,2, sharey=True)
labels=('Uplink','Downlink')
fig2.suptitle('Applications Down/Up link', fontsize=20)
#******************    
ax2.set_title('App 1')
#ax2.set_xlabel('seconds')
ax2.set_ylabel('CDF')
ax2.grid(True)
ax2.plot(fgfS1,fgfS2, 'b')
ax2.plot(bgfS1,bgfS2, 'c')
ax2.set_xscale('log')
ax2.legend(labels,loc='best')
#******************
ax02.set_title('App 3')
ax02.set_xlabel('seconds')
ax02.set_ylabel('CDF')
ax02.grid(True)
ax02.plot(fgifS1,fgifS2, 'b')
ax02.plot(bgifS1,bgifS2, 'c')
ax02.set_xscale('log')
ax02.legend(labels,loc='best')

所以我想添加 len(bgfS1) 例如,但我仍然不知道在哪里以及如何....

【问题讨论】:

  • 您的问题与 CDF 无关,并且您提供了太多不相关的代码。基本上,您想要的是显示带有图例的附加信息 - 这是一个有效的问题,如果您的答案和代码简明扼要,而不仅仅是整个代码,您将增加快速获得答案的机会。

标签: python matplotlib plot legend


【解决方案1】:

只需将其附加到您的 labels 列表组件中,这些组件将确定最终显示的内容。

所以你想要:

ax2.legend(['{} ({})'.format(lab, cnt) for lab,cnt in izip(labels, (len(fgfS1), len(bgfS1)))],loc='best')

(这实际上只是将计数附加到每个标签)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2020-11-30
    • 2021-01-28
    • 1970-01-01
    • 2020-12-13
    • 2020-09-16
    相关资源
    最近更新 更多