Custom Yaxis plot in matplotlib python - python

Let's say if I have Height = [3, 12, 5, 18, 45] and plot my graph then the yaxis will have ticks starting 0 up to 45 with an interval of 5, which means 0, 5, 10, 15, 20 and so on up to 45. Is there a way to define the interval gap (or the step). For example I want the yaxis to be 0, 15, 30, 45 for the same data set.

import matplotlib.pyplot as plt
import numpy as np
plt.plot([3, 12, 5, 18, 45])
plt.yticks(np.arange(0,45+1,15))
plt.show()

This should work
matplotlib.pyplot.yticks(np.arange(start, stop+1, step))

Related

How to make bar plot of a list in Python

I have a list that has counts of some values and I want to make a bar plot to see the counts as bars. The list is like:
print(lii)
# Output
[46, 11, 9, 20, 3, 15, 8, 63, 11, 9, 24, 3, 5, 45, 51, 2, 23, 9, 17, 1, 1, 37, 29, 6, 3, 9, 25, 5, 43]
I want something like this plot with each list value as a bar and its value on top:
I tried the following code but it plotted the list as a series:
plt.figure(figsize=(30, 10))
plt.plot(lii)
plt.show()
Any help is appreciated.
I believe you want something like this:
ax = sns.barplot(x=np.arange(len(lii)), y=lii)
ax.bar_label(ax.containers[0])
plt.axis('off')
plt.show()
You can do it using matplotlib pyplot bar.
This example considers that lii is the list of values to be counted.
If you already have the list of unique values and associated counts, you do not have to compute lii_unique and counts.
import matplotlib.pyplot as plt
lii = [46, 11, 9, 20, 3, 15, 8, 63, 11, 9, 24, 3, 5, 45, 51, 2, 23, 9, 17, 1, 1, 37, 29, 6, 3, 9, 25, 5, 43]
# This is a list of unique values appearing in the input list
lii_unique = list(set(lii))
# This is the corresponding count for each value
counts = [lii.count(value) for value in lii_unique]
barcontainer = plt.bar(range(len(lii_unique)),counts)
# Some labels and formatting to look more like the example
plt.bar_label(barcontainer,lii_unique, label_type='edge')
plt.axis('off')
plt.show()
Here is the output. The label above each bar is the value itself, while the length of the bar is the count for this value. For example, value 9 has the highest bar because it appears 4 times in the list.

bar graph with wrong width

I want to create a bar graph for a dataframe contains multiple categories, with a different color for each category. Below is my simplified code and resulting graph. The top subplot is a regular bar graph in one color, the bottom subplot is color coded but the bar width is messed up. Any suggestions? Thanks!
import random
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'Cat': [1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4],
'A': [2, 3, 6, 7, 9, 10, 15, 18, 22, 23, 24, 25],
'B': random.sample(range(1, 20), 12)})
fig = plt.figure(figsize=(15, 15/2.3))
ax = plt.subplot(2, 1, 1)
plt.bar(df.A, df.B)
plt.xlim(0, 30)
ax = plt.subplot(2, 1, 2)
for cat in df.Cat.unique():
df_ = df.loc[(df.Cat==cat), :]
plt.bar(df_.A, df_.B, width=0.5)
plt.xlim(0, 30)
plt.show()

How do I customize the colours in the bars using custom number set in matplotlib?

I am trying to add colors to the bar according to the integer value, lets say the values are 1 to 20, 1 will be the lightest and 20 will be the darkest, but none of the colors can be the same, so far I am at using an incorrect colorbar method:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'values': [17, 16, 16, 15, 15, 15, 14, 13, 13, 13]})
df.plot(kind='barh')
plt.imshow(df)
plt.colorbar()
plt.show()
But it gives a strange result of:
How do I fix it?
I just realized using plt.barh and colormaps provide better plots, use:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'values': [0, 0, 0, 0, 0, 17, 16, 16, 15, 15, 15, 14, 13, 13, 13]})
df = df.sort_values(by='values').reset_index(drop=True)
s = df['values'].replace(0, df.loc[df['values'] != 0, 'values'].min())
s = s.sub(s.min())
colors = (1 - (s / s.max())).astype(str).tolist()
plt.barh(df.index, df['values'].values, color=colors)
plt.show()
Which gives:

Formating timestams on x axis using matplotlib

How to format timestamps on x axis as "%Y-%m-%d %H:%M". ts is list of timestamps and how to show on x axis values:
"2018-5-23 14:00", "2018-5-23 14:15" and "2018-5-23 14:30".
My current chart shows:
23 14:00, 23 14:05, 23 14:10, 23 14:15, 23 14:20, 23 14:25, 23 14:30.
import datetime
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
ts = [datetime.datetime(2018, 5, 23, 14, 0), datetime.datetime(2018, 5, 23, 14, 15), datetime.datetime(2018, 5, 23, 14, 30)]
values =[3, 7, 6]
plt.plot(ts, values, 'o-')
plt.show()
Firstly, you need to set your x ticks so that only the values you want will be displayed. This can be done using plt.xticks(tick_locations, tick_labels).
To get the dates in the right format you need to specify a DateFormatter and apply it to your x axis.
Your code would look like:
import datetime
import matplotlib.pyplot as plt
from matplotlib import style
from matplotlib.dates import DateFormatter
style.use('fivethirtyeight')
ts = [datetime.datetime(2018, 5, 23, 14, 0), datetime.datetime(2018, 5, 23, 14, 15), datetime.datetime(2018, 5, 23, 14, 30)]
values =[3, 7, 6]
plt.plot(ts, values, 'o-')
plt.xticks(ts, ts) # set the x ticks to your dates
date_formatter = DateFormatter("%Y-%m-%d %H:%M") # choose desired date format
ax = plt.gca()
ax.xaxis.set_major_formatter(date_formatter)
plt.show()

Matplotlib twinx for different scales

I am using matplotlib twinx for graphing multiple variables on the same axes. But I have a problem, for which I can't find a solution. For simplicity, I have attached little code and graph plotted by that code below.
In this picture, I need those bars to be displayed at the bottom of axes as shown in picture 2. But in picture 2, yticks of ax1t remained as the same. I also need them to be displayed at the bottom. How can I do that?
Code:
import matplotlib.pyplot as plt
import numpy as np
fig, ax1 = plt.subplots()
ax1.plot([4, 2, 8, 6, 4, 7, 3, 5])
ax1t = ax1.twinx()
ax1t.bar(np.arange(8), [45, 42, 55, 36, 58, 45, 48, 62], alpha=0.4)
plt.show()
Picture 2
I guess this is what you want -
import matplotlib.pyplot as plt
import numpy as np
fig, ax1 = plt.subplots()
ax1.plot([4, 2, 8, 6, 4, 7, 3, 5])
ax1t = ax1.twinx()
ax1t.bar(np.arange(8), [45, 42, 55, 36, 58, 45, 48, 62], alpha=0.4)
ax1t.set_ylim([10,500])
ax1t.set_yticks([10, 50, 90])
plt.show()
Change the y axis scale using set_ylim and then explicitly pass the y ticks using set_yticks. You play around with the parameters to adjust it according to your convenience.
from matplotlib examples
import matplotlib.pyplot as plt
import numpy as np
f, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True)
ax1.plot([4, 2, 8, 6, 4, 7, 3, 5])
ax2.bar(np.arange(8), [45, 42, 55, 36, 58, 45, 48, 62], alpha=0.4)
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
plt.show()
You could also use Plotly library, which could easily do that with great visualisation.
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Scatter(
x=[0, 1, 2, 3, 4, 5],
y=[1.5, 1, 1.3, 0.7, 0.8, 0.9]
)
trace2 = go.Bar(
x=[0, 1, 2, 3, 4, 5],
y=[1, 0.5, 0.7, -1.2, 0.3, 0.4]
)
data = [trace1, trace2]
py.iplot(data, filename='bar-line')
Result (it is .png format, therefore not interactive)

Categories