saifuddin778
saifuddin778

Reputation: 7277

Include histograms in matplotlib scatterplot

I am doing my scatter plots in matplotlib and they are generating well. However, to display the correlations between x and y, I need to add histograms on both axes as subplots (like shown in this example). Since the code in the example is a bit complicated, so I am not able to follow how to get my scatter plots to have these. Here is my code:

import matplotlib.pyplot as plt
import numpy
from statlib import stats
from math import log

x1=numpy.loadtxt("a.txt")
x2 = numpy.loadtxt("b.txt")


x1 = numpy.array(x1)
x2 = numpy.array(x2)
x1 = x1.reshape(82,296)
x2 = x2.reshape(82,296)
x = numpy.vstack([x1, x2])


y1=numpy.loadtxt("c.txt")
y2=numpy.loadtxt("d.txt")

y1 = numpy.array(y1)
y2 = numpy.array(y2)

y1 = y1.reshape(82,296)
y2 = y2.reshape(82,296)

y = numpy.vstack([y1, y2])


plot = plt.scatter(y,x)
plt.grid('on')
plt.xlabel('X')
plt.ylabel('Y')
plt.ylim(-20,1000)
plt.title('Scatter Plot')

plt.show()

Any help would be REALLY helpful.

Upvotes: 0

Views: 1945

Answers (1)

unutbu
unutbu

Reputation: 879471

Copy the code from the example.

Locate the line

axScatter.scatter(x, y)

This creates the scatter plot. Compare it with your line

plot = plt.scatter(y,x)

They are basically the same except that the x and y are reversed. So to connect your code to the example, Simply replace

x = np.random.randn(1000)
y = np.random.randn(1000)

(from the example) with your code defining y and x.

Upvotes: 1

Related Questions