Matplotlib twinx for different scales - python

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)

Related

Python - Bland-Altman Plot with Text Customization

I am trying to Create the Bland-Altman Plot with the text having on the left side of the plot instead of having it as the default configuration on the right hand side
This is my code
import pandas as pd
df = pd.DataFrame({'A': [5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9,
10, 11, 13, 14, 14, 15, 18, 22, 25],
'B': [4, 4, 5, 5, 5, 7, 8, 6, 9, 7, 7, 11,
13, 13, 12, 13, 14, 19, 19, 24]})
import statsmodels.api as sm
import matplotlib.pyplot as plt
#create Bland-Altman plot
f, ax = plt.subplots(1, figsize = (8,5))
sm.graphics.mean_diff_plot(df.A, df.B, ax = ax)
#display Bland-Altman plot
plt.show()
So I want to have the "mean", the "SD+" and the "SD-" on the left side of the X-axis, not on the right.
thanks for your help or any suggestions!
I don't know, but I can use pyplot so:
mean_diff = (df.A-df.B).mean()
diff_range = (df.A-df.B).std()*1.96
plt.figure(figsize = (9,6))
plt.scatter(df.A, df.A-df.B, alpha=.5)
plt.hlines(mean_diff, df.A.min()-2, df.A.max()+2, color="k", linewidth=1)
plt.text(
df.A.min()-1, mean_diff+.05*diff_range, "mean diff: %.2f"%mean_diff,
fontsize=13,
)
plt.hlines(
[mean_diff+diff_range, mean_diff-diff_range],
df.A.min()-2, df.A.max()+2, color="k", linewidth=1,
linestyle="--"
)
plt.text(
df.A.min()-1, mean_diff+diff_range+.05*diff_range,
"+SD1.96: %.2f"%(mean_diff+diff_range),
fontsize=13,
)
plt.text(
df.A.min()-1, mean_diff-diff_range+.05*diff_range,
"-SD1.96: %.2f"%(mean_diff-diff_range),
fontsize=13,
)
plt.xlim(df.A.min()-2, df.A.max()+2)
plt.ylim(mean_diff-diff_range*1.5, mean_diff+diff_range*1.5)
plt.xlabel("Means", fontsize=15)
plt.ylabel("Difference", fontsize=15)
plt.show()
result:

how to change the scale of the x-axis so that the orange and blue graphs are displayed correctly

I cannot correctly depict two graphs: orange and blue. I've read the documentation, tried changing the values until nothing comes out.
How to show these graphs, as in 1 picture, together with others correctly
I get it like this
My code
My code:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0.264, 0.331, 0.397, 0.417, 0.438, 0.45, 0.459, 0.466])
y = np.array([0.01, 0.1, 1, 2, 4, 6, 8, 10])
# creating scatter plot with both negative
# and positive axes
plt.plot(x, y, marker='o')
x = np.array([0.375, 0.435, 0.494, 0.512, 0.53, 0.541, 0.548, 0.564])
y = np.array([0.01, 0.1, 1, 2, 4, 6, 8, 10])
plt.plot(x, y, marker='o')
x2points=np.array([-3.672, -3.733, -3.793, -3.811, -3.828, -3.839, -3.846, -3.852])
y2points = np.array([-0.01, -0.1, -1, -2, -4, -6, -8, -10])
plt.plot(x2points, y2points, marker = 'o')
x2points = np.array([-14.86, -14.931, -14.998, -15.018, -15.039, -15.051, -15.06, -15.067])
y2points = np.array([-0.01, -0.1, -1, -2, -4, -6, -8, -10])
plt.plot(x2points, y2points, marker='o')
# adding vertical line in data co-ordinates
plt.axvline(0, c='black', ls='--')
# adding horizontal line in data co-ordinates
plt.axhline(0, c='black', ls='--')
plt.xticks([-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1])
plt.yticks([-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# visualizing the plot using plt.show() function
plt.show()
The result I want to get
enter image description here
The red and green curve use an x-range from -15 to -4, while the orange and blue curves have a very limited range between 0.25 and 0.55. Displaying them together on the same graph will necessarily lead to the compression you see.
You can draw two subplots, and move them close together while sharing the y-axis. That way, different x-axes can be used:
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15, 4), sharey=True,
gridspec_kw={'wspace': 0})
x = np.array([0.264, 0.331, 0.397, 0.417, 0.438, 0.45, 0.459, 0.466])
y = np.array([0.01, 0.1, 1, 2, 4, 6, 8, 10])
# creating scatter plot with both negative
# and positive axes
ax2.plot(x, y, marker='o')
x = np.array([0.375, 0.435, 0.494, 0.512, 0.53, 0.541, 0.548, 0.564])
y = np.array([0.01, 0.1, 1, 2, 4, 6, 8, 10])
ax2.plot(x, y, marker='o')
x2points = np.array([-3.672, -3.733, -3.793, -3.811, -3.828, -3.839, -3.846, -3.852])
y2points = np.array([-0.01, -0.1, -1, -2, -4, -6, -8, -10])
ax1.plot([], []) # 2 dummy plots to move the color cycle
ax1.plot([], [])
ax1.plot(x2points, y2points, marker='o')
x2points = np.array([-14.86, -14.931, -14.998, -15.018, -15.039, -15.051, -15.06, -15.067])
y2points = np.array([-0.01, -0.1, -1, -2, -4, -6, -8, -10])
ax1.plot(x2points, y2points, marker='o')
# adding vertical line in data co-ordinates
# plt.axvline(0, c='black', ls='--')
# adding horizontal line in data co-ordinates
ax1.axhline(0, c='black', ls='--')
ax2.axhline(0, c='black', ls='--')
# set ticks and data limiits
ax1.set_xticks(range(-15, 0))
ax1.set_xlim(xmax=0)
ax1.set_yticks(range(-10, 11))
ax2.set_xlim(xmin=0)
plt.tight_layout()
plt.show()

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()

Custom Yaxis plot in matplotlib 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))

How do I draw a chart with lines through various points, using matplotlib.pyplot?

I am new to Python. I borrowed this code from an example, and put in my own numbers:
import matplotlib.pyplot as plt
plt.plot(1, 9, 'rs', 2, 8, 'bs', 7, 3, 'g^', 9, 1, 'r^')
plt.title('Chart of 4 companies')
plt.axis([0, 12, 0, 12])
plt.grid(True)
plt.show()
This works great, it shows me a chart, and it shows 4 points on the chart. But is it possible to show the line going from point [0,0] to these lines? I wanted to make a point about cosine similarity, but I am failing badly.
In case you want a straight line from (0,0) to a point (x,y) you can plot it simply via
plt.plot([0,x],[0,y])
So the whole code may look like this
import matplotlib.pyplot as plt
plt.plot(1, 9, 'rs', 2, 8, 'bs', 7, 3, 'g^', 9, 1, 'r^')
plt.plot([0,1], [0,9], 'r')
plt.plot([0,2], [0,8], 'b')
plt.plot([0,7], [0,3], 'g')
plt.plot([0,9], [0,1], 'r')
plt.title('Chart of 4 companies')
plt.axis([0, 12, 0, 12])
plt.grid(True)
plt.show()

Categories