I am unable to see any labels on this plot and I have specified labels for each axis. The same thing is happening with the x axis showing as 0,2,4, rather than 0,1,2,3,4 etc.
For reference - I am using this within my PySimpleGUI code:
import matplotlib.pyplot as plt
data1= [0,1,2,3,4,5,6,7,8,9]
data2= [10,20,30,40,50,60,70,133,121,123]
data3=[100,324,121,432,232,543,332,543,534,122]
data4=[100,312,111,111,322,443,545,122,345,122]
#plt.style.use('dark_background')
title="my graph"
plt.figure(figsize=(8,5))
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='white'
plt.rcParams['font.size'] = '8'
plt.bar(data1,data2, color= 'blue' ,width=0.5,label="data2")
plt.twinx()
plt.plot(data1, data3, label="data 3 label")
plt.plot(data1, data4,label="data4",color='green')
plt.xlabel("my x axis label",fontsize =8)
plt.title(title,fontsize=8)
plt.tight_layout()
fig = plt.gcf()
print(fig)
Please could someone point me in the right direction?
Thank you
Some clean-up using the object-oriented interface:
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='white'
plt.rcParams['font.size'] = '8'
fig, ax = plt.subplots(figsize=(8, 5))
ax.bar(data1,data2, color= 'blue' ,width=0.5,label="data2")
ax2 = ax.twinx()
ax2.plot(data1, data3, label="data 3 label")
ax2.plot(data1, data4,label="data4",color='green')
ax.set_xlabel("my x axis label",fontsize =8)
ax.set_xticks(data1)
ax.set_title(title,fontsize=8)
fig.tight_layout()
Output:
Perhaps better to use MultipleLocator for the tick positions (credit for the idea to #JohanC):
from matplotlib.ticker import MultipleLocator
...
ax.xaxis.set_major_locator(MultipleLocator(1))
Try using plt.axes() to separate it, as shown
import matplotlib.pyplot as plt
data1= [0,1,2,3,4,5,6,7,8,9]
data2= [10,20,30,40,50,60,70,133,121,123]
data3=[100,324,121,432,232,543,332,543,534,122]
data4=[100,312,111,111,322,443,545,122,345,122]
#plt.style.use('dark_background')
title="my graph"
plt.figure(figsize=(8,5))
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='white'
plt.rcParams['font.size'] = '8'
ax = plt.axes()
ax.bar(data1,data2, color= 'blue' ,width=0.5,label="data2")
ax2 = plt.twinx()
ax2.plot(data1, data3, label="data 3 label")
ax2.plot(data1, data4,label="data4",color='green')
ax2.set_xlabel("my x axis label",fontsize =8)
plt.title(title,fontsize=8)
plt.tight_layout()
fig = plt.gcf()
print(fig)
Related
I am using secondary y-axis and cmap color but when I plot together the color bar cross to my plot
here is my code
fig,ax1=plt.subplots()
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10,60), c='Lifetime1 (a)', colormap='jet_r', vmin=0, vmax=25, ax=ax1)
graph.axhline(0, color='k')
plt.xticks(rotation=90)
ax2 = ax1.twinx()
ax2.plot(df_Combine_min_select1["CumEnergy1 (kWH)"])
plt.show()
and here is my plotting
anyone can help how to solve this issue?
Thank you
When you let pandas automatically create a colorbar, you don't have positioning options. Therefore, you can create the colorbar in a separate step and provide the pad= parameter to set a wider gap. Default, pad is 0.05, meaning 5% of the width of the subplot.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
df_Combine = pd.DataFrame({'Parameter2': np.random.rand(10) * 10,
'NPV (MM €)': np.random.rand(10),
'Lifetime1 (a)': np.random.rand(10) * 25,
})
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10, 60), c='Lifetime1 (a)',
colormap='jet_r', vmin=0, vmax=25, ax=ax1, colorbar=False)
plt.colorbar(ax1.collections[0], ax=ax1, pad=0.1)
ax2 = ax1.twinx()
ax2.plot(np.random.rand(10))
plt.show()
How can I solve this? I want to do 4 subplots with matplotlib, I have used the subplot option but the result is just a big plot. I don't have idea what is the problem. I want to see four subplots, each one with title, and a suptitle for them.
I don't have idea how can I solve it?
Can you help me please to fix it?
Thanks a lot
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from matplotlib.collections import LineCollection
import matplotlib.patches as mpatches
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as tkr
from pylab import text
with open("file1.txt") as f:
m1 = map(float,f)
with open ("file2.txt") as f:
m2 = map(float, f)
fig, ax = plt.subplots(sharey='row')
fig.set_figwidth(18) #Width figure
fig.set_figheight(12) #Height figure
plt.rcParams['figure.dpi'] = 300
plt.subplots_adjust(wspace=0.18, hspace=0.2)
fig.suptitle('PLOTS', y=0.93, fontsize=15)
# Plot
plt.subplot(421)
y = np.array(m1)
x = np.arange(len(y))
threshold = 0.5
segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)
segments_y = np.r_[y[0], y[1:-1].repeat(2), y[-1]].reshape(-1, 2)
linecolors = ['red' if y_[0] > threshold and y_[1] > threshold else 'blue'
for y_ in segments_y]
segments = [zip(x_, y_) for x_, y_ in zip(segments_x, segments_y)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,268)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(x), max(x)+1, 10))
plt.grid()
plt.tight_layout()
# Plot
plt.subplot(423)
p = np.array(m2)
o = np.arange(len(p))
threshold = 0.5
segments_o = np.r_[o[0], o[1:-1].repeat(2), o[-1]].reshape(-1, 2)
segments_p = np.r_[p[0], p[1:-1].repeat(2), p[-1]].reshape(-1, 2)
linecolors = ['red' if p_[0] > threshold and p_[1] > threshold else 'blue'
for p_ in segments_p]
segments = [zip(o_, p_) for o_, p_ in zip(segments_o, segments_p)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,383)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(o), max(o)+1, 10))
plt.grid()
plt.tight_layout()
plt.show()
#plt.savefig('figure.png', format='png', bbox_inches="tight", dpi=300)
How can I solve this?
where is the problem?
You need to specify the number of plots you want to be created by matplotlib.pyplot.subplots,
nrows = 2
ncols = 2
fig, ax = plt.subplots(nrows, ncols, sharey='row')
which will create an array of axes instances with shape (nrows, ncols). You can then plot to individual axes via
ax[0,0].plot(...)
Although in order to set tick properties, labels, etc for the axes you need to use the axes versions of the functions instead of the pyplot versions. I.e.
ax[0, 0].set_xticks(...)
# instead of
plt.xticks(...)
ax[0, 0].set_title(...)
# instead of
plt.title(...)
ax[0, 0].set_xlabel(...)
# instead of
plt.set_xlabel(...)
I'm trying to draw clean graphs using matplotlib.
Here is my code:
fig = plt.figure(figsize = (6,6))
plt.grid(True)
plt.xlabel('time (s)',fontweight='bold')
plt.ylabel('density',fontweight='bold')
plt.plot(data1, data2, color = 'y', linewidth = 2)
plt.show()
the floats in data2 lies between 0.0001 and 0.001, so When I do this, the y axis has ticks like '0.0001' '0.0002' etc.
How can I force the ticks to be in scientific notation ('1e-3', '1e-4' etc. ) ?
thx :)
This sets it like 1e-04:
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
data1 = [1,2,3,4,5]
data2 = [1e4,3e4,4e4,2e4,5e4]
fig = plt.figure(figsize = (6,6))
plt.grid(True)
plt.xlabel('time (s)',fontweight='bold')
plt.ylabel('density',fontweight='bold')
plt.plot(data1, data2, color = 'y', linewidth = 2)
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))
plt.show()
I would like to create a tsplot, where the x and the y axis are the same length. in other words the aspect ratio of the graph should be 1.
this dos not work:
fig, ax = plt.subplots()
fig.set_size_inches(2, 2)
sns.tsplot(data=df, condition=' ', time='time', value='value', unit=' ', ax=ax)
You could change the aspect ratio of your plots by controlling the aspect
parameter of a matplotlib object as shown:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(22)
sns.set_style("whitegrid")
gammas = sns.load_dataset("gammas")
fig = plt.figure()
ax = fig.add_subplot(111, aspect=2) #Use 'equal' to have the same scaling for x and y axes
sns.tsplot(time="timepoint", value="BOLD signal", unit="subject",
condition="ROI", data=gammas, ax=ax)
plt.tight_layout()
plt.show()
A little more direct is ax.set_box_aspect(1)1
I want to display yaxis on both side. In matplotlib 1.2, I can use following code:
ax.tick_params(labelright = True)
However, there is no method tick_params for Axes in matplotlib 0.99. Is there any simple way to do this in 0.99?
Tks
EDIT
I got this solution followed by #Brian Cain's
ax2 = ax1.twinx()
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels([t.get_text() for t in ax1.get_yticklabels()])
Here is an example from matplotlib docs with differing scales on each Y axis. You could use the same scale if you preferred.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
plt.show()