6 examples of 'how to plot bar graph in python using csv file' in Python

Every line of 'how to plot bar graph in python using csv file' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
42def generate_graph():
43 with open('../../data/ram.dat', 'r') as csvfile:
44 data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
45 for row in data_source:
46 # [0] column is a time column
47 # Convert to datetime data type
48 a = datetime.strptime((row[0]),'%H:%M:%S')
49 x.append((a))
50 # The remaining columns contain data
51 free_mem.append(str((int(row[1])/1024)+(int(row[4])/1024)+(int(row[5])/1024)))
52 used_mem.append(str((int(row[2])/1024)-(int(row[4])/1024)-(int(row[5])/1024)))
53 buffer_mem.append(str(int(row[4])/1024))
54 cached_mem.append(str(int(row[5])/1024))
55
56 # Plot lines
57 plt.plot(x,free_mem, label='Free', color='g', antialiased=True)
58 plt.plot(x,used_mem, label='Used', color='r', antialiased=True)
59 plt.plot(x,buffer_mem, label='Buffer', color='b', antialiased=True)
60 plt.plot(x,cached_mem, label='Cached', color='c', antialiased=True)
61
62 # Graph properties
63 plt.xlabel('Time',fontstyle='italic')
64 plt.ylabel('Memory (MB)',fontstyle='italic')
65 plt.title('RAM usage graph')
66 plt.grid(linewidth=0.4, antialiased=True)
67 plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True)
68 plt.autoscale(True)
69
70 # Graph saved to PNG file
71 plt.savefig('../../graphs/ram.png', bbox_inches='tight')
281def generate_bar_chart(chart_data, bottoms=None, bar_width=0.4, labels=[], orientation='vertical'):
282 """
283 Creates a bar chart for revenue using chart_data.
284 """
285 fig, ax = plt.subplots(figsize=(12, 6))
286
287 # Get the revenue data from the ValOp objects.
288 indices = np.arange(len(chart_data))
289
290 # Plot.
291 with sb.axes_style('whitegrid'):
292 if bottoms is None:
293 if orientation == 'horizontal':
294 ax.barh(indices, chart_data, height=bar_width, color=PALETTE)
295 plt.yticks(indices, labels, rotation=0)
296 ax.set_xticklabels(['{:,}'.format(int(x)) for x in ax.get_xticks().tolist()]) # Comma separator for y-axis tick labels.
297 else:
298 ax.bar(indices, chart_data, width=bar_width, color=PALETTE)
299 plt.xticks(indices, labels, rotation=0)
300 ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()]) # Comma separator for y-axis tick labels.
301 else:
302 if orientation == 'horizontal':
303 ax.barh(indices, chart_data, left=bottoms, height=bar_width, color=PALETTE)
304 plt.yticks(indices, labels, rotation=0)
305 ax.set_xticklabels(['{:,}'.format(int(x)) for x in ax.get_xticks().tolist()]) # Comma separator for y-axis tick labels.
306 # ax.set_xlim(0, max(chart_data))
307 else:
308 ax.bar(indices, chart_data, bottom=bottoms, width=bar_width, color=PALETTE)
309 plt.xticks(indices, labels, rotation=0)
310 ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()]) # Comma separator for y-axis tick labels.
311 # ax.set_ylim(0, max(chart_data))
312
313 # sb.despine(offset=10, trim=True)
314
315 return fig, ax
1120def plot_bar_chart(page, datasets, dataset_labels, dataset_colors,
1121 x_group_labels, err,
1122 title=None, xlabel='Bins', ylabel='Counts'):
1123 '''
1124 Plot a bar chart into page, using the supplied data.
1125 '''
1126 assert len(datasets) == len(err)
1127 assert len(datasets) == len(dataset_colors)
1128 assert len(datasets) == len(dataset_labels)
1129 for dataset in datasets:
1130 assert len(dataset) == len(datasets[0])
1131 assert len(dataset) == len(x_group_labels)
1132
1133 num_x_groups = len(datasets[0])
1134 x_group_locations = pylab.arange(num_x_groups)
1135 width = 1.0 / float(len(datasets)+1)
1136
1137 figure = pylab.figure()
1138 axis = figure.add_subplot(111)
1139 bars = []
1140
1141 for i in xrange(len(datasets)):
1142 bar = axis.bar(x_group_locations + (width*i), datasets[i], width,
1143 yerr=err[i], color=dataset_colors[i],
1144 error_kw=dict(ecolor='pink', lw=3, capsize=6,
1145 capthick=3))
1146 bars.append(bar)
1147
1148 if title is not None:
1149 axis.set_title(title)
1150 if ylabel is not None:
1151 axis.set_ylabel(ylabel)
1152 if xlabel is not None:
1153 axis.set_xlabel(xlabel)
1154
1155 axis.set_xticks(x_group_locations + width*len(datasets)/2)
1156 x_tick_names = axis.set_xticklabels(x_group_labels)
1157 rot = 0 if num_x_groups == 1 else 15
1158 pylab.setp(x_tick_names, rotation=rot, fontsize=10)
1159 axis.set_xlim(-width, num_x_groups)
1160 y_tick_names = axis.get_yticklabels()
1161 pylab.setp(y_tick_names, rotation=0, fontsize=10)
1162
1163 axis.legend([bar[0] for bar in bars], dataset_labels)
1164 page.savefig()
1165 pylab.close()
200def readPlot():
201 dataFolder = 'tut8_data/'
202 batchLabel = 'tauWeight'
203
204 params, data = readBatchData(dataFolder, batchLabel, loadAll=0, saveAll=1, vars=None, maxCombs=None)
205 plot2DRate(dataFolder, batchLabel, params, data, 'synMechTau2', 'connWeight', 'M', "'M' pop rate (Hz)")
142def plot_bar(xs, ys, names, error_ys=None, xlabel='x', ylabel='y', title=''):
143
144 layout = go.Layout(
145 title=title,
146 xaxis=dict(
147 title=xlabel,
148 titlefont=dict(
149 family='Courier New, monospace',
150 size=18,
151 color='#7f7f7f'
152 )
153 ),
154 yaxis=dict(
155 title=ylabel,
156 titlefont=dict(
157 family='Courier New, monospace',
158 size=18,
159 color='#7f7f7f'
160 )
161 )
162 )
163
164 traces = []
165
166 for (i, y) in enumerate(ys):
167 kwargs = {}
168 if names:
169 kwargs['name'] = names[i]
170 if error_ys:
171 kwargs['error_y'] = dict(
172 type='data', # or 'percent', 'sqrt', 'constant'
173 array=error_ys[i], # values of error bars
174 visible=True
175 )
176 trace = go.Bar(
177 x = xs[i],
178 y = y,
179 **kwargs
180 )
181 traces.append(trace)
182
183 data = traces
184 print 'data', data
185
186 fig = go.Figure(data=data, layout=layout)
187 # disp = iplot(fig, filename=datetime.now().strftime('%a, %d %b %Y %H:%M:%S +0000'))
188 disp = iplot(fig) # offline mode, no need for filename.
158def plot_bars():
159 ylim = plt.ylim()
160 for x in np.arange(0, t[-1], presentation_time):
161 plt.plot([x, x], ylim, 'k--')

Related snippets