I am currently creating a graph that that analyzes the correlation of absorption and concentration (Beer's law). While creating the graph, I've ran into a few problems, and I am now stuck. My plots are not showing up within my graph. Is it due to placement error? If possible, I would like to leave the ticks, labels, and title in the same (or similar format). Sorry in advance for the sloppiness, trying to get the function down before I make it pretty. But anyways, here is the code:
#importing matplotlib to create a graph
import matplotlib.pyplot as plt
#ploting out the points while labeling the graph
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-
03],[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks([1, 2, 3, 4, 5, 6, 7], [str('1.95E-03'), str('9.75E-04'),
str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'),
str('1.95E-06')])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
Your xticks are completely out of the range where your data lives. Remove the line which sets the xticks and your plot is fine
import matplotlib.pyplot as plt
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-03],
[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
If you want to use your custom ticks, you need to set them in the data range, i.e. somewhere between 0 and 0.002 and not between 1 and 7.
Your data has x values well below 0.01, while your ticks start at 1, so your data will be to the left of the plot. I would suggest using a logarithmic x axis, just like the example below. This will also fix the problem with the x values being of different orders of magnitude. Note that I also put the tick strings in reverse order, assuming that you mistakenly wrote them the other way round. If not, please just go ahead and re-reverse them!
#importing matplotlib to create a graph
import matplotlib.pyplot as plt
x = [1.95e-06, 9.75e-06, 1.95e-05, 9.75e-05, 1.95e-04, 9.75e-04, 1.95e-03]
#ploting out the points while labeling the graph
plt.semilogx(x ,[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks(x, [str('1.95E-03'), str('9.75E-04'), str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'), str('1.95E-06')], rotation=45)
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.tight_layout()
plt.savefig('points.png')
plt.show()
The first argument to plt.xticks should be x-coords (not tick indexes).
Related
Very recently I have been tasked with ploting a derivative using Python and matplotlib. This is my code:
x=np.linspace(-100,100,num=50)
funcion=(56*(x**3))-(38.999*(x**2))+(4.196*x-0.15)
plt.plot(x, funcion)
The resulting plot is this:
Plot generated in Python
At first sight, the graph looks okay, but is not correct, given that the graph is suposed to look like this:
Correct plot
How can I fix this? I have tried changing the linespace a bunch of times, and the results are the same.
I've tried to plot a derivate in matplotlib and the graph is incorrect.
The problem is not with matplotlib, but instead the range of x values you chose. If you look at your own picture, the xvalues are ranging from around -2 to 2, so if I do the same and play with the plotting bounds I get:
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-2,2,101)
funcion=(56*(x**3))-(38.999*(x**2))+(4.196*x-0.15)
plt.plot(x, funcion)
plt.axvline(0, color = 'k')
plt.axhline(0, color = 'k')
plt.xlim([-0.8, 1.4])
plt.ylim([-3.5, 3])
which gives
graph
how do I make this graph infill all the square around it? (I colored the part that I want to take off in yellow, for reference)
Normally I use two methods to adjust axis limits depending on a situation.
When a graph is simple, axis.set_ylim(bottom, top) method is a quick way to directly change y-axis (you might know this already).
Another way is to use matplotlib.ticker. It gives you more utilities to adjust axis ticks in your graph.
https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html
I'm guessing you're using a list of strings to set yaxis tick labels. You may want to set locations (float numbers) and labels (string) of y-axis ticks separatedly. Then set the limits on locations like the following snippet.
import matplotlib.pyplot as plt
import matplotlib.ticker as mt
fig, ax = plt.subplots(1,1)
ax.plot([0,1,2], [0,1,2])
ax.yaxis.set_major_locator(mt.FixedLocator([0,1,2]))
ax.yaxis.set_major_formatter(mt.FixedFormatter(["String1", "String2", "String3"]))
ax.set_ylim(bottom=0, top=2)
It gives you this: generated figure
Try setting the min and max of your x and y axes.
I am trying to display a chart using matplotlib. But my labels are so big that they are overlapping each other. I want to show it cleanly no overlapping. How can I do that? I am now using below code:
import matplotlib.pyplot as plt
x = ['jdwdw723#gmail.com' ,'emcast.test10#gmail.com', 'pbChinaTester#clp.com']
y = [10,25,6]
plt.plot(x,y)
plt.xlabel("loginId")
plt.ylabel("times appeared in the data")
plt.title("loginId Graph")
plt.tight_layout()
plt.show()
I tried your example code, and it doesn't seem to be overlapping there. There are many possibilities. One, commonly used, is to rotate the labels.
You can do it like this:
plt.xticks(rotation=45)
There are more ideas in Changing the “tick frequency” on x or y axis in matplotlib? and in reducing number of plot ticks.
I created an example notebook here, feel free to duplicate and play with it.
I want make a graph of a part of the values of a dictionary.
I already stored the necessary values in a variable, but I just don't understand how to put them in a simple graph with just the numbers 1 to 500 on the x-axis and my values on the y-axis.
%matplotlib inline
import matplotlib.pyplot as plt
# Plot frequencies of the most 500 words
frequencies = freqs_sorted[len(freqs_sorted)-500:len(freqs_sorted)]
Everything I tried so far resulted in an empty graph. Thanks in advance!
From the matplotlib tutorial:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.plot(range(1, 501), frequencies)
plt.show()
P.S. In matplotlib you often have several ways to draw whatever you want. It is just one of them. Here is shorter version from #gboffi:
plt.plot(frequencies)
plt.show()
In the following code snippet:
import numpy as np
import pandas as pd
import pandas.rpy.common as com
import matplotlib.pyplot as plt
mtcars = com.load_data("mtcars")
df = mtcars.groupby(["cyl"]).apply(lambda x: pd.Series([x["cyl"].count(), np.mean(x["wt"])], index=["n", "wt"])).reset_index()
plt.plot(df["n"], range(len(df["cyl"])), "o")
plt.yticks(range(len(df["cyl"])), df["cyl"])
plt.show()
This code outputs the dot plot graph, but the result looks quite awful, since both the xticks and yticks don't have enough space, that it's quite difficult to notice both 4 and 8 of the cyl variable output its values in the graph.
So how can I plot it with enough space in advance, much like you can do it without any hassles in R/ggplot2?
For your information, both of this code and this doesn't work in my case. Anyone knows the reason? And do I have to bother to creating such subplots in the first place? Is it impossible to automatically adjust the ticks with response to the input values?
I can't quite tell what you're asking...
Are you asking why the ticks aren't automatically positioned or are you asking how to add "padding" around the inside edges of the plot?
If it's the former, it's because you've manually set the tick locations with yticks. This overrides the automatic tick locator.
If it's the latter, use ax.margins(some_percentage) (where some_percentage is between 0 and 1, e.g. 0.05 is 5%) to add "padding" to the data limits before they're autoscaled.
As an example of the latter, by default, the data limits can be autoscaled such that a point can lie on the boundaries of the plot. E.g.:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(10), 'ro')
plt.show()
If you want to avoid this, use ax.margins (or equivalently, plt.margins) to specify a percentage of padding to be added to the data limits before autoscaling takes place.
E.g.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(10), 'ro')
ax.margins(0.04) # 4% padding, similar to R.
plt.show()