问题
I have a list of names: ['joe','brian','stephen']
i would like to create a bar chart in jupyter with names as indexes and the bar showing the numbers of letters in each name. How do I create a series which I can call ".plot(kind='bar')" on and get a bar chart like described?
回答1:
import numpy as np
import matplotlib.pyplot as plt
bars = ['joe','brian','stephen']
height = [len(m) for m in bars]
y_pos = np.arange(len(bars))
plt.bar(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
plt.xticks(y_pos, bars)
plt.show()
回答2:
You can try this,
import matplotlib.pyplot as plt
x = ['joe','brian','stephen']
y = [len(m) for m in x]
plt.bar(x, y)
plt.show()
回答3:
You can create a dataframe using your list of names and then apply len
function.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'names':['joe','brian','stephen']},dtype=str)
df['name_len'] = df['names'].apply(len)
df.plot(kind='bar',x='names')
plt.show()
来源:https://stackoverflow.com/questions/53827212/how-do-i-create-a-series-that-i-can-create-a-bar-chart-from