This question already has answers here:
Plot some numbers in x axis
(3 answers)
plot with custom text for x axis points
(3 answers)
Force python axis to show specific numbers
(2 answers)
Closed 1 year ago.
I am starting to use the matplotlib library to generate simple graphs. In one of my tests something happens to me that does not allow me to obtain the graph that I expect. Coming to the point, I have two value arrays (circle and g) and I would like to join each of their values. The problem comes when I input the x-axis values. I would like only the values of my array g to be on the x axis, but the following happens:
In my code I have the following:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
circle = [0.002,0.013,0.035]
g = [5,25,50]
ax.scatter(g[0], circle[0], color = 'g', marker = "o")
x = np.array([0,1,2,3])
my_xticks = [0,5,25,50]
plt.xticks(x, my_xticks)
plt.show()
Could someone help me fix this?
The problem was that when calling plt.xticks(), you passed [0, 1, 2, 3] as the x-tick values, and you passed the tick values you really wanted as the tick labels. Instead, pass the tick values you want as the first argument, and omit the second argument. The tick labels will be strings of the tick values by default.
import matplotlib.pyplot as plt
circle = [0.002, 0.013, 0.035]
g = [5, 25, 50]
my_xticks = [0] + g
fig, ax = plt.subplots()
ax.scatter(g, circle, color='g', marker='o')
plt.xticks(my_xticks)
plt.show()
Related
This question already has answers here:
Update marker sizes of a scatter plot
(2 answers)
Closed 6 months ago.
Let's say I have the function
x = [1,2,3,4,5,6,7,8,9]
y = [1,2,3,4,5,6,7,8,9]
def dofig(x,y):
fig, ax = plt.subplots()
A = ax.plot(x,y,'o-' , markersize=5)
return fig, ax, A
fig, ax, A = dofig(x,y)
ax.set_xlabel('X')
Is there a way to change the marker size or other attributes of the returned figure made using plt.plot()?
Why the list of attributes of scatter is much larger than plot?
This is an edited question. I thanks the comments, and just wonder if there is some trick to do that.
You can make a call to ax.set_sizes(sizes) where "sizes" is a list the length of your points which vales are equal to the size you want those points to be:
Default Graph
x = [1,2,3,4,5,6,7,8,9]
y = [1,2,3,4,5,6,7,8,9]
scatter = plt.scatter(x,y,s=50)
Updated marker size:
scatter = plt.scatter(x,y,s=50)
sizes = [300]*len(x)
scatter.set_sizes(sizes)
This question already has answers here:
fill_between with matplotlib and a where condition of two lists
(1 answer)
Matplotlib fill_between edge effect with `where` argument
(1 answer)
Fill between x and baseline x position in Matplotlib
(1 answer)
How to avoid gaps with matplotlib.fill_between and where
(1 answer)
Closed 1 year ago.
I'm plotting a blackbody curve and would like to fill in the area under the curve in the range of between 3 and 5 micron. However, I'm not sure how to use the fill_between or fill_betweenx plt commands here
import numpy as np
import matplotlib.pyplot as plt
from astropy import units as u
from astropy.modeling import models
from astropy.modeling.models import BlackBody
from astropy.visualization import quantity_support
bb = BlackBody(temperature=308.15*u.K)
wav = np.arange(1.0, 50.0) * u.micron
flux = bb(wav)
with quantity_support():
plt.figure()
plt.plot(wav, flux, lw=4.0)
plt.fill_between(wav,flux, min(flux), color = 'red')
plt.show()
This plots a fill under the whole curve, but only the 3-5micron part is desired to be filled.
example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 100) # Sample data.
# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots() # Create a figure and an axes.
print(x)
ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend() # Add a legend.
plt.fill_between(x[:5],x[:5])
plt.show()
You can change the value 5 and play with it, you'll understand quickly. first parameter is Y positions , second is X positions.
fill_betweenx is just the same, but it will fill the other way around.
edit: As said in comments, it is better to use plt.fill_between(x,x, where = (x>0)&(x<0.2)). Both works, second solution is more explicit.
This question already has answers here:
How to annotate end of lines using python and matplotlib?
(3 answers)
Closed 3 years ago.
I have multiple lines plotted on an xy scatter plot
There are more than the number of colours in my palette, which means the colours start cycling.
I have played with using other palettes but the visibility suffers.
An idea I would like to explore now is to add the legend labels at the point where each line intercepts the right-hand y-axis.
Something like this:
Is this possible to achieve with matplotlib and/or seaborn?
Quick one, with use of the other answer to this question
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
names = ['foo', 'bar', 'foobar']
N_size = 100
fig, ax = plt.subplots(1, 1)
df = pd.DataFrame(map(lambda x: pd.Series(np.cumsum(np.random.rand(N_size) - 0.5), name=x), names)).T
df.plot(ax=ax)
ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
ax2.set_yticklabels(df.columns)
plt.show()
This question already has answers here:
How to plot one single data point?
(4 answers)
Closed 4 years ago.
I have a graph which represents the sentiments of the values in a column of pandas dataframe. Given a sentence, I want to highlight the corresponding sentiment value on the graph/plot. I am looking for an output similar to the image below:
You can use pyplot.scatter and pass single values in for x and y. Here's an example:
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
x_data = np.linspace(0,3.5,100)
y_data = [-x * (x - 3.2) for x in x_data]
plt.plot(x_data, y_data, color='#0000ff', zorder=0)
x_point = x_data[20]
y_point = y_data[20]
plt.scatter(x_point, y_point, color='#ff0000', zorder=1)
Produces:
This question already has answers here:
Pyplot sorting y-values automatically
(2 answers)
Closed 5 years ago.
For a class project I am plotting a barchart. I have a python list with a bunch of labels (even, odd, squares, powers of 3, etc) and a numpy array to hold probabilities associated with each label (in the same order as the labels list). When I plot my chart
labels = ["even", "odd", "squares", "powers of 3"]
fig, ax = plt.subplots()
ax.barh(labels, probability)
it puts the barchart values in reverse alphabetical order so instead of it being ordered even, odd, squares it is ordered squares, powers of 3, odd, even, etc. How can I keep my plot in the same order as my list?
The first parameter in Axes.barh is the vertical coordinates of the bars, so you'll want something like
fig, ax = plt.subplots()
y = np.arange(len(labels))
ax.barh(y, probability)
ax.set_yticks(y)
ax.set_yticklabels(labels)
This way, the bars will be ordered following the order of your list from top to bottom. If you want it the other way around, you could simply do
fig, ax = plt.subplots()
y = np.arange(len(labels))
ax.barh(y, probability)
ax.set_yticks(y)
ax.set_yticklabels(labels)
ax.invert_yaxis()
instead.
Edit: Given #ImportanceOfBeingErnest's comment, I should note that the above was tested with matplotlib 2.1.1.