Statistics
| Branch: | Revision:

peerstreamer-logs-analyzer / lib / plot_utilities.py @ c39a768e

History | View | Annotate | Download (5.12 KB)

1
from utilities import *
2
from pandas import *
3
import matplotlib.pyplot as plt
4
import colorsys 
5
import struct
6

    
7
def plotOrderedErrorBar(x,y,yerr=None,xlab=None,ylab=None,tit=None,label=None,on_x=False):
8
        if on_x:
9
          perm = sorted(range(len(x)), key=lambda k: x[k])
10
        else:
11
                perm = sorted(range(len(y)), key=lambda k: y[k])
12
        x = [x[i] for i in perm]
13
        y = [y[i] for i in perm]
14
        if yerr != None:
15
                yerr = [yerr[i] for i in perm]
16

    
17
        if label:
18
                plt.plot(range(0,len(x)), y,label=label, linestyle="dashed", marker="o")
19
        else:
20
                plt.plot(range(0,len(x)), y, linestyle="dashed", marker="o")
21

    
22
        plt.errorbar(range(0,len(x)),y,yerr = yerr, linestyle="None", marker="None", color="green")
23
        plt.xticks(range(0,len(x)),x)
24
        plt.xlim(-1,len(x))
25
        plt.grid()
26
        if xlab:
27
                plt.xlabel(xlab)
28
        if ylab:
29
                plt.ylabel(ylab)
30
        if tit:
31
                plt.title(tit)
32
        return x
33

    
34
def plotHeatMap(mat,xlab=None,ylab=None,tit=None,maxv=None,title_distance=1.1,min_color=None):
35
        if maxv:
36
                maximum = maxv
37
        else:
38
                maximum = mat.max().max()
39
        minimum = mat.min().min() 
40
        #mat = (mat-minimum)/(maximum-minimum)
41

    
42
        fig, ax = plt.subplots()
43
        my_cmap = plt.cm.get_cmap('Reds')
44
        if min_color:
45
                my_cmap.set_under(min_color)
46
                minimum += 0.00000001 # in order to set min values to white
47

    
48
        heatmap = plt.pcolor(mat, cmap=my_cmap, alpha=1, vmin=minimum, vmax=maximum)
49
        # to make a squared graph
50
        x0,x1 = ax.get_xlim()
51
        y0,y1 = ax.get_ylim()
52
        ax.set_aspect((x1-x0)/(y1-y0))
53

    
54
        plt.colorbar()
55
#        fig = plt.gcf()
56
#        fig.set_size_inches(8, 11)
57

    
58
        ax.set_frame_on(False)
59

    
60
        ax.set_yticks(np.arange(mat.shape[0]) + 0.5, minor=False)
61
        ax.set_xticks(np.arange(mat.shape[1]) + 0.5, minor=False)
62

    
63
        ax.invert_yaxis()
64
        ax.xaxis.tick_top()
65

    
66
        ax.set_xticklabels(list(mat.columns), minor=False)
67
        ax.set_yticklabels(mat.index, minor=False)
68

    
69
        plt.xticks(rotation=90)
70
        ax.grid(False)
71
        #ax = plt.gca()
72

    
73
        #legend
74
#        cbar = plt.colorbar(heatmap)
75
#        cbar.ax.get_yaxis().set_ticks([])
76
##        for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
77
##                        cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
78
##        cbar.ax.text(.5, 0.95, maximum, ha='center', va='center')
79
#        cbar.ax.get_yaxis().labelpad = 15
80
##        cbar.ax.set_ylabel('# of contacts', rotation=270)
81
#        cbar.ax.set_ylabel('Interval: '+str(round(minimum,2))+" - "+str(round(maximum,2)))
82

    
83
        if xlab:
84
                plt.xlabel(xlab)
85
                ax.xaxis.set_label_position('top')
86
        if ylab:
87
                plt.ylabel(ylab)
88
        if tit:
89
                plt.text(0.5, title_distance, tit, horizontalalignment='center',  fontsize=20,  transform = ax.transAxes)
90
#                plt.title(tit)
91

    
92
def scientific_formatter(x, p):
93
        scale_pow = 2
94
        return "%.2f" % (x * (10 ** scale_pow))
95

    
96
def rgb_gradient_color(value,min_value,max_value):
97
        if value > max_value:
98
                value = max_value
99
        value = rescale(value,min_value,max_value,0.0,0.1)
100
        value = 0.1 - value 
101
        rgb = colorsys.hsv_to_rgb(value,1,1)
102
        RGB = tuple(int(i*255) for i in rgb)
103
        return '#'+ struct.pack('BBB',*RGB).encode('hex')
104

    
105
def make_legend(minv,maxv,levels,text="Legend: "):
106
        legend = "<"
107
        legend += "<table border='0' cellborder = '1' cellspacing='0' cellpadding='0'>\
108
                        <tr> <td colspan='1' ><b>"+text+" </b></td> \
109
                        <td colspan='1' ><b>"+str(minv)+"</b></td> "
110
        for i in range(0,levels):
111
                legend += "<td colspan='1' bgcolor='"+rgb_gradient_color(i+1,1,levels)+"' width='5'></td>"
112

    
113
        legend += "<td colspan='1' ><b>"+str(maxv)+"</b></td> </tr> </table>"
114
        legend += ">"
115
        return legend
116

    
117

    
118
def plotBarGraph(dataframe,xlab=None,ylab=None,tit=None,ylim=None):
119
        dataframe.plot(kind='bar',legend=False) #,transparency=True)
120
        if xlab:
121
                plt.xlabel(xlab)
122
        if ylab:
123
                plt.ylabel(ylab)
124
        if tit:
125
                plt.title(tit)
126

    
127
        lims=plt.axis()
128
        if ylim:
129
                plt.ylim(ylim)
130
        ax = plt.gca()
131
        ax.set_autoscale_on(False)
132
        plt.grid()
133

    
134
def plotHistogram(h,b,xlab=None,ylab=None,tit=None,log_scale=False,label=None):
135
        if label:
136
                plt.plot(b[:-1],h,label=label)
137
        else:
138
                plt.plot(b[:-1],h)
139
        if log_scale:
140
                plt.xscale('log')
141
        if xlab:
142
                plt.xlabel(xlab)
143
        if ylab:
144
                plt.ylabel(ylab)
145
        if tit:
146
                plt.title(tit)
147

    
148
def plotDictAsBox(f,dicto):
149
        #print dicto
150
        values = dicto.values()
151
        x = dicto.keys()
152
        ax = f.add_subplot(111)
153
        bp = ax.boxplot(values)
154
        ax.set_xticklabels(x)
155
        plt.xticks(rotation=90)
156

    
157
def plotHistFrequencies(h,b,xlabel,title=None,log_scale=False,ylabel=None,linestyle='-'):
158
        sb = plt.subplot(1,1,1)
159

    
160
        sb.yaxis.tick_left()
161
        sb.yaxis.set_label_position("left")
162
#        sb.set_ylim([0,1])
163
#        plot1 = sb.plot(b[:-1],h,label="Frequency distribution")
164
        plot1 = sb.plot(b[:-1],h,linewidth=2,color='blue',linestyle=linestyle)
165
        if log_scale:
166
                sb.set_xscale('log')
167
        plt.legend(loc='lower right')
168
        if ylabel:
169
                plt.ylabel(ylabel)
170
        else:
171
                plt.ylabel("Number of samples")
172
        plt.xlabel(xlabel)
173
        sb.set_ylim([0,max(h)])
174

    
175
        sumSamples = []
176
        partialSum = 0.0
177
        for v in h:
178
                        partialSum += v
179
                        sumSamples.append(partialSum)
180
        sbSum=sb.twinx()
181
        sbSum.yaxis.tick_right()
182
        sbSum.yaxis.set_label_position("right")
183
        sbSum.set_ylim([0,1])
184
        plot2 = sbSum.plot(b[:-1], (np.array(sumSamples)/sum(h)),color='black',linewidth=2,linestyle=linestyle)
185
        #plot2 = sbSum.plot(b[:-1], (np.array(sumSamples)/sum(h)),color='green',label="Integral")
186
        if log_scale:
187
                sb.set_xscale('log')
188

    
189
        if title:
190
                plt.title(title)
191
        plt.ylabel("Probability")
192
        plt.legend(loc='upper right')
193
        sbSum.yaxis.grid(color='gray', linestyle='dashed')
194
        sbSum.set_axisbelow(True)