简体   繁体   中英

issue in making a bar chart using matplotlib or mpld3 in pyspark

I have a list list = [['0-50',4],['50-100',11],['100-150',73],['150-200',46]] and I want to show it on a histogram using mpld3 in python pyspark . The first part in each element of list is range which will be on x-axis of histogram and the second part is the number of people in that range which will on y-axis. How can I make a bar chart using either matplotlib or mpld3 in pyspark ?

UPDATE: I tried below code based on [this] example 1 and it displays the bar chart but the output is visually very bad with lots of grey colored area around the plot boundary. How can I get it look clear and better in terms of visualization?

import numpy as np
import matplotlib.pyplot as plt

list = [['0-50',4],['50-100',11],['100-150',73],['150-200',46]]
n_groups = len(list)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35

opacity = 0.4
error_config = {'ecolor': '0.3'}

number = []
ranges = []
for item in list:
    number.append(item[1])
    ranges.append(item[0])

rects1 = plt.bar(index, number, bar_width,
                 alpha=opacity,
                 color='b',
                 error_kw=error_config)

plt.xlabel('Number')
plt.ylabel('range')
plt.xticks(index + bar_width, (ranges[0],ranges[1],ranges[2],ranges[3]))
plt.legend()

plt.tight_layout()
plt.show()

A secret weapon to make matplotlib plots look good is import seaborn . This overrides the mpl defaults with something nice.

I would also make the bars bigger and move the xticks to the middle of the bars. Here is a slight tweak of your code to do so:

import numpy as np, matplotlib.pyplot as plt, mpld3, seaborn as sns

list = [['0-50',4],['50-100',11],['100-150',73],['150-200',46]]
n_groups = len(list)
index = np.arange(n_groups)

bar_width = 0.9
opacity = 0.4

number = []
ranges = []
for item in list:
    number.append(item[1])
    ranges.append(item[0])

rects1 = plt.bar(index, number, bar_width,
                 alpha=opacity,
                 color='b')

plt.xlabel('Number')
plt.ylabel('range')
plt.xticks(index + bar_width/2, (ranges[0],ranges[1],ranges[2],ranges[3]))

mpld3.display()

Here is how it looks:

在此处输入图片说明

And here is a notebook where you can see the interactivity that mpld3 adds (which is basically useless, but a little bit fun).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM