Visualizing Charts with np.arange in Visualizing Tech Stocks

Hello,

I’m trying to present the plots based on length of the daily calculated means, but the output presented in Jupyter Notebook (even in the solution reference) is shown based on the order the stocks were input for analysis and not arranged on the stocks calculated means.

# arrange keys on x axis based on length
x_pos = np.arange(len(daily_mean.keys()))
x_pos
# plot bars
plt.bar(x_pos, height)
 
# create names on the x-axis
plt.xticks(x_pos, daily_mean.keys())

# label chart
plt.xlabel("Tech_Stocks")
plt.ylabel("daily mean")
plt.title("daily mean rate of return")

# show graphic
plt.show()

The Course is Analyze Financial Data with Python and the lesson is Visualizing tech stocks here https://www.codecademy.com/paths/finance-python/tracks/visualizing-finance-data/modules/visualizing-tech-stocks/informationals/visualizing-tech-stocks

Each bar in your your plot is based on x_pos and height, if you adjusted the inputs to the order you wanted then the plot would match.

The x_pos code np.arange(len(daily_mean.keys())) is not displaying in the graph.
Instead of being arranged by mean, the stocks are each displayed and arranged by the initial string order.

Maybe I am confused!

I thought I was commanding python to arrange in the display the code by x_pos which should be the mean and height, so I thought the display should be from small to large.
I was thinking that the smallest mean would be on the left side and ordered smallest to the largest on the right of the graph.

Could you point me in the right direction on how I would command python to arrange the returns from least to greatest?

Is this matplotlib? It’ll just display them based on the details you provide, paraphrasing bits from https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html

matplotlib.pyplot.bar(x, height, …
x float or array-like: The x coordinates of the bars. See also align for the alignment of the bars to the coordinates.
height float or array-like: The height(s) of the bars.

The np.arange function just gives you a series of numbers, e.g. np.arange(5) would give you array([0, 1, 2, 3, 4]). If you pass this as the x argument for plt.bar then these are just the x-positions on the axis your bars will be placed at (based on align as docs mention).

If you wanted to change the position of the bars you could change these the x-positions with these values. Alternatively you could change the order of the height argument you pass instead (so order by mean beforehand). I think just changing the inputs is the easiest step here.

1 Like

Oh ok that makes sense, thanks!
I will create a new variable and order the returns by means using sorted()and pass it to the plt.bar function.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.