matplotlib graph legend is in reverse order (barh)
I have 15 graphs that looks like this:
As you see, the legend is in reverse order. I want to see 4 first, below that 3 etc.
My code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def plot_bars_by_data(data, title):
fig, axs = plt.subplots(8,2, figsize=(20,40))
fig.suptitle(title, fontsize=20)
fig.subplots_adjust(top=0.95)
plt.rcParams.update({'font.size': 13})
axs[7,1].remove()
column_index = 0
for ax_line in axs:
for ax in ax_line:
if column_index < len(data.columns):
column_name = data.columns[column_index]
current_column_values = data[column_name].value_counts().sort_index()
axx = ax.barh([str(i) for i in current_column_values.index],
list(current_column_values.values),
color=[colors[i] for i in range(data[column_name].value_counts().count())])
ax.legend(axx, [str(i) for i in current_column_values.index])
ax.set_title(column_name)
column_index +=1
plt.show()
# random data
df_test = pd.DataFrame([np.random.randint(2,5,size=15) for i in range(15)], columns=list('abcdefghijlmnop'))
plot_bars_by_data(df_test, "testing")
I tried to just reverse the legend list, but it is reversing the colors as well. I'm using Python 3.6 in Jupyter python notebook. Any ideas?
See also questions close to this topic
-
how to display contents of text file one line at a time via timer using python on windows?
this is the code.
def wndProc(hWnd, message, wParam, lParam): if message == win32con.WM_PAINT: hdc, paintStruct = win32gui.BeginPaint(hWnd) dpiScale = win32ui.GetDeviceCaps(hdc, win32con.LOGPIXELSX) / 60.0 fontSize = 36 # http://msdn.microsoft.com/en-us/library/windows/desktop/dd145037(v=vs.85).aspx lf = win32gui.LOGFONT() lf.lfFaceName = "Times New Roman" lf.lfHeight = int(round(dpiScale * fontSize)) #lf.lfWeight = 150 # Use nonantialiased to remove the white edges around the text. # lf.lfQuality = win32con.NONANTIALIASED_QUALITY hf = win32gui.CreateFontIndirect(lf) win32gui.SelectObject(hdc, hf) rect = win32gui.GetClientRect(hWnd) # http://msdn.microsoft.com/en-us/library/windows/desktop/dd162498(v=vs.85).aspx win32gui.DrawText( hdc, **'Glory be to the Father, and to the son and to the Holy Spirit.',** -1, rect, win32con.DT_CENTER | win32con.DT_NOCLIP | win32con.DT_VCENTER ) win32gui.EndPaint(hWnd, paintStruct) return 0
.where it says the "glory be to the father.." prayer I would like that string to actually display a few different prayers on a timer. what I mean is I want to save short prayers to a text file and have the line where it says "glory be.." to change to a new prayer every 60 seconds cycling through a few prayers such as the serenity prayer etc.
-
How to plot the frequency of my data per day in an histogram?
I want to plot the number occurences of my data per day. y represent the id of my data. x represent the timestamp which I convert to time and day. But I can't make the correct plot. import matplotlib.pyplot as plt plt.style.use('ggplot') import time
y=['5914cce8-fad6-45d1-bec2-e59e62823617', '1c2067e0-5173-4a1d-8a75-b18267ee4598', 'db6830ff-fa9c-4aa5-b71e-f6da9333f357', '672cc9d5-360e-4451-bb7c-03e3d0bd8f0d', 'fb0f8122-fffc-47fe-a87a-b2b749df173b', '558e96ca-0222-40c7-acc0-e444f7663f53', 'c3f86fd5-eac3-48d3-a44c-b325f30b6139', '21dd849f-895f-4cf5-a168-45a4c1a9fbf9', 'e3b4cd56-e291-4671-93b6-d2226ee82ae7', '01346c48-a8c4-43d1-ac02-1efa33ca0f4e', '23b78b0f-85be-4ca7-99f4-1a5add76c12e', 'b1c036c0-0c2b-4170-a170-8fd0add0dec2', '74737546-e9c3-4126-bcb2-4d34503421ca', '342991f5-ec87-4c9d-83eb-9908f3e221aa', '4fdcd83a-eb68-4e26-b79b-753c5e022a4e', 'b7fbeca9-9416-43c4-9e90-9e71acc1eaba', '27c9d358-a3ef-4c69-ba89-eac16d8d3bdb', 'ef982c4b-a115-48a1-aef1-2f672d7f1f00', 'efedede2-9bb4-4c52-98b1-8b03070df3fd', 'eb03ae1b-4cde-409c-8d34-2a16a8be30d2'] x=['1548143296750', '1548183033872', '1548346185194', '1548443373507', '1548446119319', '1548446239441', '1548446068267', '1548445962159', '1548446011209', '1548446259465', '1548446180380', '1548239985290', '1548240060367', '1548240045347', '1547627568993', '1548755333313', '1548673604016','1548673443843', '1548673503914', '1548673563975'] date=[] for i in x: print(i) print() i=i[:10] print(i) readable = time.ctime(int(i)) readable=readable[:10] date.append(readable) print(date) plt.hist(date,y) plt.show()
-
mysql.connector.errors.ProgrammingError: Error in SQL Syntax
I'm using the Python MySQL connector to add data to a table by updating the row. A user enters a serial number, and then the row with the serial number is added. I keep getting a SQL syntax error and I can't figure out what it is.
query = ("UPDATE `items` SET salesInfo = %s, shippingDate = %s, warrantyExpiration = %s, item = %s, WHERE serialNum = %s") cursor.execute(query, (info, shipDate, warranty, name, sn, )) conn.commit()
Error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE serialNum = '1B0000021A974726'' at line 1
"1B0000021A974726" is a serial number inputted by the user and it is already present in the table.
-
How to merge different time-series plot into a 2D in Python
I have three different time-series data of the following format where the first column is timestamp and the second column is the value.
0.086206438,10 0.086425551,12 0.089227066,20 0.089262508,24 0.089744425,30 0.090036815,40 0.090054172,28 0.090377569,28 0.090514071,28 0.090762872,28 0.090912691,27
For reproduciability, I have shared the three time-series data I am using here.
From column 2, I wanted to read current row and compare it with the value of the previous row. If it is greater, I keep comparing. If the current value is smaller than the previous row's value continue, I take the difference. Let me make it clear. For example in the above sample record I provided, the seventh row (28) is smaller than the value in the sixth row (40) - so it will be (40-28 =12).
Here is my sample code.
import numpy as np import pandas as pd import csv import numpy as np import scipy.stats import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from statsmodels.graphics.tsaplots import plot_acf, acf protocols = {} types = {"data1": "data1.csv", "data2": "data2.csv", "data3": "data3.csv"} for protname, fname in types.items(): arr = [] arr1 = [] with open(fname, mode='r', encoding='utf-8-sig') as f: reader = csv.reader(f, delimiter=",") for i in reader: arr.append(int(i[1])) arr1.append(float(i[0])) arr, arr1 = np.array(arr), np.array(arr1) diffs = np.diff(arr) diffs1 = np.diff(arr1) diffs1 = diffs1[diffs > 0] diffs = diffs[diffs > 0] # To keep only the increased values protocols[protname] = { "rtime": np.array(arr1), "rdata": np.array(arr), "data": diffs, "timediff": diffs, } ## change in time for protname, values in protocols.items(): d = values["rdata"] t = values["rtime"] d = np.diff(d, 1) #/ d[:-1] t = np.diff(t, 1) plt.plot(t, d, ".", label=protname, alpha=0.5) plt.xlabel("Changes in time") plt.ylabel("differences") plt.legend() plt.show()
This gives me the following plots
How can we plot the differences versus the change in time (column onw) in a two-dimensitional (2D) graph of the three data I included separately?
-
Matplotlib - Fill_Between doesn't seem work
I'm new to python and learned a ton over the past 2 weeks. I have just started learning and experimenting with matplotlib.pylot. In my code, I have 3 seperate simple graphs on the same plot, in the third graph there are 2 lines. I am trying to have a green fill_between when y2 > y3, and red fill_between when y3 > y2. I have taken a look at other code, and they look identical to mine, but for some reason it doesn't work. Any help?
There are a few commented lines, they are just experimentation.
import matplotlib.pyplot as plt import random from matplotlib import style style.use('fivethirtyeight') def create_points(nPoints): xs = [] ys = [] for i in range(nPoints): rand = random.randrange(0,3*nPoints) xs.append(i) ys.append(rand) return xs, ys x,y = create_points(200) x1,y1 = create_points(200) x2, y2 = create_points(200) x3, y3 = create_points(200) fig = plt.figure() ax1 = plt.subplot2grid((6,1), (0,0), rowspan = 1, colspan = 1) plt.title('Subplot2grid Method') plt.ylabel('Plot 1') ax2 = plt.subplot2grid((6,1), (1,0), rowspan = 4, colspan = 1, sharex = ax1) plt.ylabel('Plot 2') ax2_xtwin = ax2.twinx() ax3 = plt.subplot2grid((6,1), (5,0), rowspan = 1, colspan = 1, sharex = ax1) plt.xlabel('x') plt.ylabel('Plot 3') ax2_xtwin.fill_between(x,0,y, facecolor = '#0079a3', alpha = 0.4) #ax2v.axes.yaxis.set_ticklables([]) ax2_xtwin.grid(False) ax2_xtwin.set_ylim(0, 1.5*max(y)) ax3.plot(x2, y2, x2, y3, linewidth = 1, label = 'x2y2 plot', color = 'k') #ax3.plot(x3, y3, linewidth = 1, label = 'x3y3 plot', color = 'firebrick') ax3.fill_between(x2, y2, y3, where = (y2 >= y3), facecolor = 'darkgreen', edgecolor = 'g', alpha = 0.5, interpolate = True) ax3.fill_between(x2, y2, y3, where = (y2 <= y3), facecolor = 'firebrick', edgecolor = 'r', alpha = 0.5, interpolate = True) #Print Points ax1.plot(x, y, linewidth = 1, label = 'xy plot', color = 'gold') ax2.plot(x1, y1, linewidth = 1, label = 'x1y1 plot', color = 'sandybrown') #ax3.plot(x2, y2, linewidth = 1, label = 'x2y2 plot', color = 'darkgreen') #ax3.plot(x3, y3, linewidth = 1, label = 'x3y3 plot', color = 'firebrick') plt.subplots_adjust(left = 0.15, bottom = 0.1, right = 0.9, top = 0.9, wspace = 0.2, hspace = 0) plt.show()
-
How to turn a set of data to a matrix and vectors
Suppose I have this huge set of data in a .txt file that has the following structure: first and the second column represents a discrete bidimensional domain, and the third column represents the values calculated on each point of the discrete X and Y axis. Example given below
x y z -1 -1 100 -1 0 50 -1 1 100 0 -1 50 0 0 0 0 1 50 1 -1 100 0 -1 50 1 1 100
It seems stupid, but I've been struggling to turn this data into vectors and matrices like X = [-1, 0, 1], Y = [-1, 0, 1] and Z = [[100, 50, 100], [50, 0, 50], [100, 50, 100]]. I went through many technics and methods using numpy, but coudn't manage to make it!
As a bonus: would turning this data into vectors and matrices, like I described, be a good way to plot it in a 3dscatter ou 3dcountour type using matplotlib?
-
Longest path in unweighted undirected graph starting and finishing in the same vertex
I have a problem in which I need to find the longest path. Given an unveighted undirected graph. Starting from a given vertex I need to visit as many vertices as possible and finish in the same one without visiting each of them more then once.
Most of the algorithms I found were for a special case (acyclic, directed etc.). An idea can be to find Hamiltonian cycle for every subset of the vertices (the subset can be generated with backtrack). But I guess there must be a far better algorithm.
-
Search JPA complex object for nested object based on its value
Lets assume we have a complex JPA relation, a fraction of which looks like this:
@MappedSuperclass public class DiffEntity { private String diffId; public DiffEntity() { this.diffId = UUID.randomUUID().toString(); } //... } @Entity @Inheritance(strategy = InheritanceType.JOINED) public class ParentEntity extends DiffEntity { @Id @GeneratedValue private long id; @Column private String name; //... } @Entity public class Construct extends ParentEntity { @Column private String variable; @OneToMany(mappedBy = "construct", cascade = CascadeType.ALL) private List<Partconstruct> partconstructs; //... } @Entity public class Partconstruct extends ParentEntity { @OneToMany(mappedBy = "partconstruct", cascade = CascadeType.ALL) private List<Field> fields; @OneToMany(mappedBy = "partconstruct", cascade = CascadeType.ALL) private List<Hardparameter> hardparameters; @ManyToOne @JoinColumn(name = "construct_id") private Construct construct; //... } @Entity public class Field extends ParentEntity { @Column private int fieldSize; @ManyToOne @JoinColumn(name = "partconstruct_id") private Partconstruct partconstruct; //... } @Entity public class Hardparameter extends ParentEntity { @Column private String value; @ManyToOne @JoinColumn(name = "partConstruct_Id") private Partconstruct partConstruct; //... }
We are concerned with
Construct
type objects.Construct
is deeply cloned and persisted, having all its nested objects on the object graph being cloned too and getting a newId
(primary key). On every clone thediffId
(fromDiffEntity
entity) stays the same (it serves the purpose of correlating objects for a diffing feature).How would it be possible to search and get a reference for a specific
DiffEntity
given we have the below:- a reference to the
Construnct
instance - type of the nested object
diffId
we are after.
I have tried different versions of object graph traversers with reflection, which will work for a small in size
Construct
object, but once it becomes too big performance is very slow.Is there any magic on the entity manager itself to achieve that ?
- a reference to the
-
Create a surface plot without actually displaying it in Matplotlib
I would like to create a surface plot without actually displaying it. I just want to export the graph to a PNG. Here is the relevant code:
import numpy from matplotlib import pyplot, cm from mpl_toolkits.mplot3d import Axes3D from pylab import figure, axes, pie, title, show fig = pyplot.figure(figsize=(11, 7), dpi=100) ax = fig.gca(projection='3d') ax.set_xlim(0, 2) ax.set_ylim(0, 1) ax.view_init(30, 225) ax.set_xlabel('$x$') ax.set_ylabel('$y$') X, Y = numpy.meshgrid(x, y) surf = ax.plot_surface(X, Y, p[:], rstride=1, cstride=1, cmap=cm.viridis, linewidth=0, antialiased=False) pyplot.pause(.001) pyplot.savefig("images/blah" + str(counter)+".png")
Note that the variables are all fine and there is no bug (it's a lot of math so I cut it for ease of reading) I just can't figure out how to export to a PNG without displaying the figure itself.
-
In base R plot, how can deploy multiple pchs to the same symbol?
plot(1, pch = 19, cex = 3, col = "red") points(1, pch = 1, cex = 3, col = "black", lwd = 2) legend("top", "sym", pch = 19, col = "red", cex = 2, pt.cex = 4) legend("top", "sym", pch = 1, col = "black", cex = 2, pt.cex = 4)
In R, a black borderline can be added to a solid red circle like:
Then, how can I use the symbol with added types for the legend?
As the code shows, legends cannot be added but overlapped.
Thanks.
-
Sharing the same label for two plots with line and point markers in legend
I have a plot with two different series of curves which I am going to plot them using points and lines. I would like to have a legend such that the line and point markers share the same label.
I have tried this suggestion which works well if my both series of plots have different point types, instead of line and points. The code that I am currently using, with improper legend, is
import numpy as np import matplotlib.pyplot as plt Vs = np.array([0.5, 1, 1.5, 2]) Xs = np.array([[ 0.5, 0.2, 0.7], [ 0.5, 0.3, 0.9], [ 0.5, 0.5, 0.4], [ 0.5, 0.7, 0.4], [ 0.5, 0.9, 0.7], [ 1, 0.15, 0.9], [ 1, 0.35, 0.6], [ 1, 0.45, 0.6], [ 1, 0.67, 0.5], [ 1, 0.85, 0.9], [ 1.5, 0.1, 0.9], [ 1.5, 0.3, 0.7], [ 1.5, 0.76, 0.3], [ 1.5, 0.98, 0.4], [ 2, 0.21, 0.5], [ 2, 0.46, 0.4], [ 2, 0.66, 0.3], [ 2, 0.76, 0.5], [ 2, 0.88, 0.4], [ 2, 0.99, 0.4]]) f, axs = plt.subplots(1, 1, figsize=(2.5,3)) #------------------------------------- axs.set_xlim(0.38,1.0) axs.set_ylim(0.0,4.0) colors = plt.cm.gist_ncar(np.linspace(0,1,max(Vs)+3)) for idx,Val in enumerate(Vs): axs.plot(Xs[Xs[:,0] == Val ,1], Xs[Xs[:,0] == Val ,2],'s',label=r"$Y={}$".format(Val), ms=3, color=colors[idx]) axs.plot(Xs[Xs[:,0] == Val ,1], Xs[Xs[:,0] == Val ,2]*Val/0.3,'-', label=r"$Y={}$".format(Val), ms=3, color=colors[idx]) axs.set_ylim(0.0,4.0) axs.set_ylabel(r"$Y$ ", labelpad=2) axs.set_xlabel(r"$X$ ", labelpad=2) axs.set_yticks([0,0.5,1.0,1.5,2.0, 2.5, 3.0, 3.5, 4.0]) axs.set_xticks([0,0.5,1.0]) axs.legend(fontsize=6, loc=2, numpoints = 1, labelspacing=0.2,handletextpad=0.2, frameon=False) f.savefig("tmp.pdf") plt.show()
Do you any suggestions to resolve this issue?
-
Break legend in two columns while keeping shape override
I have a
ggplot
problem. Here is the example data:df <- data.frame(x = rep(1:5,5), type2 = c(rep(letters[1:2],each = 10),rep("c",5)), type1 = rep(LETTERS[1:5],each = 5), value = unlist(lapply(-2:2,function(a){rnorm(5,mean = a, sd = 1)}))) library(ggplot2) plotcolor <- c( "#99d8c9","#2ca25f","#cbc9e2","#9e9ac8","#e34a33") p <- ggplot(df,aes(x,value,color = type1,fill = type1,shape = type2))+ geom_point(size = 5)+ theme_light()+ labs(title = "", color = "Method", fill = "Method", shape = "")+ geom_hline(yintercept = 0)+ guides(colour = guide_legend(override.aes = list(shape = c(21,21,24,24,22), linetype = c(rep("blank",5)), fill = plotcolor, color = plotcolor)))+ scale_shape(guide = FALSE)+ scale_colour_manual(values = plotcolor) p
Now I want to split the legend into two columns, for space reasons. I tried
p + guides(color=guide_legend(ncol=2))
but it remove the
override
part of my legend, letting just points:p + guides(color=guide_legend(ncol=2), fill =guide_legend(ncol=2) , shape = guide_legend(ncol=2))
didn't work either. Does anyone have an idea on how to deal with this particular problem?
-
reversing a array in PYTHON and prints the sum of the elements of array A with the corresponding elements of the reverse of array A
Can anyone solve this in python?
write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A. If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].
Input Format:
The first line of the input contains a number N representing the number of elements in array A. The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)
Output Format:
Print the resultant array elements separated by a space. (no space after the last element)
Example:
Input:
4 2 5 3 1
Output:
3 8 8 3
Explanation:
Here array A is [2,5,3,1] os reverse of this array is [1,3,5,2] and hence the resultant array is [3,8,8,3]
-
How to extract components from a bundled main.js file
I had lost all files of my ionic application. Only I have is the bundled main.js file build using @ionic/app-scripts. Is there any way to get my angular components back from the main.js file. I've tried using reverse-sourcemap and debundle. But didn't works. Is there any other solution.
-
Need help in reversing a banner loop JavaScript
All, I have been racking my brain for longer than I care, to admit trying to reverse this function. I have a loop set up so my slideshow starts on load, stops on hover, and can be navigated with next and previous buttons. When you switch directions, slides come from both directions and reset to one.
I'm pretty certain that this has to do with
var bannerStatus
being a global variable and resetting to one when changing directions. Is there any way to make the value not reset? Can I use a function to permanently update a global variable, or should I make one huge function that goes both ways? Here is my banner.js for this project.function bannerLoop() { if (bannerStatus === 1) { document.getElementById("ban2").style.opacity = "0"; setTimeout(function () { document.getElementById("ban3").style.right = "100%"; document.getElementById("ban3").style.zIndex = "900"; document.getElementById("ban1").style.right = "0px"; document.getElementById("ban1").style.zIndex = "1000"; document.getElementById("ban2").style.right = "-100%"; document.getElementById("ban2").style.zIndex = "1100"; }, 500); setTimeout(function () { document.getElementById("ban2").style.opacity = "1"; }, 1000); bannerStatus++; } else if (bannerStatus === 2) { document.getElementById("ban3").style.opacity = "0"; setTimeout(function () { document.getElementById("ban1").style.right = "100%"; document.getElementById("ban1").style.zIndex = "900"; document.getElementById("ban2").style.right = "0px"; document.getElementById("ban2").style.zIndex = "1000"; document.getElementById("ban3").style.right = "-100%"; document.getElementById("ban3").style.zIndex = "1100"; }, 500); setTimeout(function () { document.getElementById("ban3").style.opacity = "1"; }, 1000); bannerStatus++; } else if (bannerStatus === 3) { document.getElementById("ban1").style.opacity = "0"; setTimeout(function () { document.getElementById("ban2").style.right = "100%"; document.getElementById("ban2").style.zIndex = "900"; document.getElementById("ban3").style.right = "0px"; document.getElementById("ban3").style.zIndex = "1000"; document.getElementById("ban1").style.right = "-100%"; document.getElementById("ban1").style.zIndex = "1100"; }, 500); setTimeout(function () { document.getElementById("ban1").style.opacity = "1"; }, 1000); bannerStatus = 1; } } function reverseBanner() { if (bannerStatus === 1) { document.getElementById("ban3").style.opacity = "0"; setTimeout(function () { document.getElementById("ban3").style.right = "100%"; document.getElementById("ban3").style.zIndex = "900"; document.getElementById("ban1").style.right = "0px"; document.getElementById("ban1").style.zIndex = "1000"; document.getElementById("ban2").style.right = "-100%"; document.getElementById("ban2").style.zIndex = "1100"; }, 500); setTimeout(function () { document.getElementById("ban3").style.opacity = "1"; }, 1000); bannerStatus++; } else if (bannerStatus === 2) { document.getElementById("ban2").style.opacity = "0"; setTimeout(function () { document.getElementById("ban2").style.right = "100%"; document.getElementById("ban2").style.zIndex = "900"; document.getElementById("ban3").style.right = "0px"; document.getElementById("ban3").style.zIndex = "1000"; document.getElementById("ban1").style.right = "-100%"; document.getElementById("ban1").style.zIndex = "1100"; }, 500); setTimeout(function () { document.getElementById("ban2").style.opacity = "1"; }, 1000); bannerStatus++; } else if (bannerStatus === 3) { document.getElementById("ban1").style.opacity = "0"; setTimeout(function () { document.getElementById("ban1").style.right = "100%"; document.getElementById("ban1").style.zIndex = "900"; document.getElementById("ban2").style.right = "0px"; document.getElementById("ban2").style.zIndex = "1000"; document.getElementById("ban3").style.right = "-100%"; document.getElementById("ban3").style.zIndex = "1100"; }, 500); setTimeout(function () { document.getElementById("ban1").style.opacity = "1"; }, 1000); bannerStatus = 1; } } document.getElementById("nxtbtn").onclick = function () { bannerLoop(); } document.getElementById("prvbtn").onclick = function () { reverseBanner(); }